【问题标题】:How to get index of Class item in array with Swift 4?如何使用 Swift 4 获取数组中类项的索引?
【发布时间】:2018-04-05 21:13:18
【问题描述】:

我的课如下所示:

struct Cur: Decodable {
    let id: String
    let name: String
    let symbol: String
    let switchVal:Bool
}

该类填充一个数组,该数组正在 UITableView 中显示。如何检测哪个开关按钮(switchVal)被切换,因此如何获取相关元素的“id”。

我正在检测 UISwitchButton 何时在这样的原型单元内切换:

@IBAction func switchBtn(_ sender: UISwitch) {
     if sender.isOn {

     }
}

【问题讨论】:

  • 与您的问题无关,但不要在您的属性中使用隐式展开的选项
  • 顺便说一句,将您的 switchVal 定义为常量 false 没有意义
  • 而 isOn 是一个非可选的 Bool。使用== true 是多余的。要检查是否不是 isOn,只需使用 if !sender.isOn
  • 也修复了,谢谢!

标签: arrays swift indexing


【解决方案1】:

您可以使用index(where:) 方法查找数组元素的索引,如下所示:

struct Cur: Decodable {
    let id: String
    let name: String
    let symbol: String
    let switchVal: Bool
}

let cur1 = Cur(id: "a", name: "john", symbol: "j", switchVal: false)
let cur2 = Cur(id: "b", name: "steve", symbol: "s", switchVal: true)
let cur3 = Cur(id: "c", name: "Carl", symbol: "c", switchVal: false)

let list = [cur1, cur2, cur3]

if let index = list.index(where: {$0.switchVal}) {
    print(list[index]) // Cur(id: "b", name: "steve", symbol: "s", switchVal: true)\n"
    print(list[index].id)  // "b\n"
}

【讨论】:

  • 您好,我相信您的代码将完美运行,并为此感谢您。但是,我收到错误“致命错误:在展开可选值时意外发现 nil”。我确信这与我的强制解包有关。必须弄清楚那些选项。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
相关资源
最近更新 更多