Arrays 如何使用Swift 4获取数组中类项的索引?

Arrays 如何使用Swift 4获取数组中类项的索引?,arrays,swift,indexing,Arrays,Swift,Indexing,我的课程如下所示: struct Cur: Decodable { let id: String let name: String let symbol: String let switchVal:Bool } 此类填充数组,数组显示在UITableView中。如何检测切换了哪个开关按钮(switchVal),因此如何获取相关元素的“id” 我检测到UISwitchButton在原型单元内的切换,如下所示: @IBAction func switchBtn(_

我的课程如下所示:

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 {

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

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"
}

与您的问题无关,但不要在属性中使用隐式展开的选项。顺便说一句,定义switchVal一个常量false没有意义,isOn是一个非可选布尔。使用
==true
是多余的。要检查是否存在,只需使用
if!sender.isOn
也解决了这个问题,谢谢!您好,我相信您的代码将完美地工作,并为此感谢您。但是,我得到了错误“致命错误:在展开可选值时意外发现nil”。我确信这和我的原力有关。我必须找出那些选项。非常感谢。