【问题标题】:Why isn't this for loop returning any non-false members?为什么这个 for 循环不返回任何非假成员?
【发布时间】: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 与 trueif 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 { ... }
  • 我猜Clientstruct 并且您将它们存储在不同的数组中。正常传递时结构会重复。

标签: arrays swift uitableview for-loop


【解决方案1】:

仅过滤掉选定的客户端:

let clientListSelected = clientList.filter { $0.isSelected }

为您的未知目的逻辑提供更简单的逻辑

let client = clientList[indexPath.row]
client.isSelected = client.s.isMultiple(of: 2)  

【讨论】:

  • 您可以在尾随闭包中省略( ).filter { $0.isSelected }
【解决方案2】:

我想我明白了。我试图将array 的所有内容与@IBAction 一起附加到下一个视图控制器,同时从array 加载数据。感谢您的回答,我也稍微修改了代码。

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多