【发布时间】:2019-10-14 09:11:02
【问题描述】:
这个 for 循环没有返回任何 true 成员。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
clientList[indexPath.row].s += 1
if clientList[indexPath.row].s % 2 == 0 {
clientList[indexPath.row].isSelected = true
} else if clientList[indexPath.row].s % 2 != 0{
clientList[indexPath.row].isSelected = false
}
}
这是for循环:
@IBAction func toClientsButton(_ sender: Any) {
for y in 0...clientList.count - 1 {
if clientList[y].isSelected == true {
clientsSelected.append(clientList[y])
}
}
}
当下一个屏幕加载时,clientsSelected 数组中没有值。
我做错了吗?
【问题讨论】:
-
我想知道,你在这里尝试什么?如果条件为假,这就是它不返回选定值的原因。可能是您没有检查
-
在 didSelectRowAt() 中,clientIndex 相对于 indexPath.row 的值是多少?我很好奇 if 和 else if 是否相互抵消。
-
无关,但很重要:不要使用
0 ... x - 1,使用0..<x。不要使用0..<array.count,使用array.indices。不要使用for i in array.indices,除非您只需要索引(这种情况很少见),而是使用for client in clientList。不要将 bool 与true(if b == true { ... }进行比较,只需使用if b { ... },除非它是可选的(其中== true成为必需的。此外,您的整个 if 语句可以替换为对filter的简单调用:selectedClients += clientList.filter { $0.isSelected }. -
此外,从 Swift 5 开始,有
Int.isMultiple(of:),这使得i % 2 == 0模式已过时。你应该只写if clientList[indexPath.row].s.isMultiple(of: 2) { ... } else { ... } -
我猜
Client是 struct 并且您将它们存储在不同的数组中。正常传递时结构会重复。
标签: arrays swift uitableview for-loop