You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中TableView Cell无法依据JSON响应的get_certificate字段正确显示文本的问题排查

问题分析与修正方案

嘿,问题出在你的switch case判断顺序上!

为什么会出错?

在Swift的switch语句中,case是按从上到下的顺序匹配的。当某个条目同时满足certificate_required == "Y"和get_certificate != nil时(比如你JSON里BUILDING分类下的子项),第一个case会先被匹配到,程序直接执行对应的逻辑,根本不会走到第二个case的判断。这就是为什么明明get_certificate存在,却还是显示(Certificate)的原因。

修正方法:调整case优先级

我们需要把更具体、优先级更高的判断放在前面——也就是先检查get_certificate是否存在(因为这是“已经上传证书”的更特殊情况),再检查certificate_required的要求。

修正后的代码如下:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AddserviceCell", for: indexPath) as! AddserviceCell
    cell.selectionStyle = .none
    let indexData = categoryData[indexPath.section].children?[indexPath.row]
    
    switch indexData {
    // 先判断:如果已经上传过证书,优先显示Uploaded
    case _ where indexData?.get_service?.get_certificate != nil:
        cell.subCatLbl.text = "\(indexData?.title ?? "") (Uploaded)"
    // 再判断:如果要求证书但还没上传,显示Certificate
    case _ where indexData?.certificate_required == "Y":
        cell.subCatLbl.text = "\(indexData?.title ?? "") (Certificate)"
    // 其他情况只显示标题
    default:
        cell.subCatLbl.text = indexData?.title ?? ""
    }
    return cell
}

额外优化建议

为了避免可选链的嵌套和空值判断的繁琐,你可以先把需要用到的属性解包出来,代码会更清晰:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "AddserviceCell", for: indexPath) as! AddserviceCell
    cell.selectionStyle = .none
    
    guard let indexData = categoryData[indexPath.section].children?[indexPath.row],
          let title = indexData.title else {
        cell.subCatLbl.text = ""
        return cell
    }
    
    if indexData.get_service?.get_certificate != nil {
        cell.subCatLbl.text = "\(title) (Uploaded)"
    } else if indexData.certificate_required == "Y" {
        cell.subCatLbl.text = "\(title) (Certificate)"
    } else {
        cell.subCatLbl.text = title
    }
    
    return cell
}

这样代码可读性更高,也能减少因可选值嵌套带来的判断错误。

内容的提问来源于stack exchange,提问作者Swift

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 21:07:41