这是poster:中的json响应
{
"result": {
"categories": [
{
"title": "ADMINISTRATION & SECRETARIAL",
"children": [
{
"id": 266,
"certificate_required": "Y",
"get_service": null
}
]
},
{
"title": "BUILDING",
"children": [
{
"id": 299,
"certificate_required": "Y",
"get_service": {
"id": 778,
"get_certificate": {
"certificate_file": "62e3a911d0233.jpg",
}
}
}
]
},
{
"id": 148,
"title": "DIGITAL DEVELOPMENT ",
"children": [
{
"id": 152,
"title": "WEB DESIGN",
"certificate_required": "N",
"get_service": null
}
]
}
]
}
}
这里我需要检查get_certificate
是否存在
所以我写了如下代码:
如果
get_certificate != nil
然后我需要出示
cell.subCatLbl.text = "(indexData?.title ?? "") (Uploaded)
但仍显示
cell.subCatLbl.text = "(indexData?.title ?? "") (Certificate).
为什么?
我哪里错了。请引导我
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categoryData[section].children?.count ?? 0
}
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 {
case _ where indexData?.certificate_required == "Y":
cell.subCatLbl.text = "(indexData?.title ?? "") (Certificate)"
case _ where ((indexData?.get_service?.get_certificate) != nil):
cell.subCatLbl.text = "(indexData?.title ?? "") (Uploaded)"
default:
cell.subCatLbl.text = indexData?.title
break
}
return cell
}
由于您的switch语句,您没有达到预期的结果。
switch语句只执行它的一个路径,确切地说是第一个匹配条件。所以每次
indexData?.certificate_required == "Y"
是真正的
cell.subCatLbl.text = "(indexData?.title ?? "") (Certificate)"
将执行,而不管接下来会发生什么。
解决方案:
要么采用切换条件,使优先级最高的条件优先出现:
case _ where ((indexData?.get_service?.get_certificate) != nil):
cell.subCatLbl.text = "(indexData?.title ?? "") (Uploaded)"
case _ where indexData?.certificate_required == "Y":
cell.subCatLbl.text = "(indexData?.title ?? "") (Certificate)"
default:
cell.subCatLbl.text = indexData?.title
break
或者在这里使用if/else方法:
if indexData?.get_service?.get_certificate != nil && indexData?.certificate_required == "Y"{
cell.subCatLbl.text = "(indexData?.title ?? "") (Uploaded)"
} else if indexData?.certificate_required == "Y"{
cell.subCatLbl.text = "(indexData?.title ?? "") (Certificate)"
} else {
cell.subCatLbl.text = indexData?.title
}