我的课程如下所示:
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 {
}
}
答案 0 :(得分:2)
您可以使用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"
}