如何从元组数组中找到元组元素的索引? iOS,Swift

时间:2016-06-19 06:36:44

标签: ios arrays swift tuples

这是在tableview cellforrowatindexpath

    var valueArray:[(String,String)] = []
    if !contains(valueArray, v: (title,status)) {
                let v = (title,status)
                valueArray.append(v)
            }

这是在didselectrowatIndexPath里面

    let cell = self.tableView.cellForRowAtIndexPath(selectedRow!)
    var newTuple = (cell!.textLabel!.text!, cell!.detailTextLabel!.text!)
    let index = valueArray.indexOf(newTuple)

但我没有得到索引。抛出错误无法将类型'(String,String)'的值转换为预期的参数类型'@noescape((String,String))throws - >布尔”。我在这里做错了什么?

2 个答案:

答案 0 :(得分:15)

可以比较元组的相等性(从Swift 2.2 / Xcode 7.3.1开始),但是 它们不符合Equatable协议。所以你有 使用基于谓词的indexOf变体来定位元组 在数组中。例如:

let valueArray = [("a", "b"), ("c", "d")]
let tuple = ("c", "d")
if let index = valueArray.indexOf({ $0 == tuple }) {
    print("found at index", index)
}

Swift 4 中,该方法已重命名为firstIndex(where:)

if let index = valueArray.firstIndex(where: { $0 == tuple }) {
    print("found at index", index)
}

答案 1 :(得分:3)

我可以选择查找元组索引

var tuple: [(key: String, value: AnyObject)] = [("isSwap", true as AnyObject), ("price", 120 as AnyObject)]
if let index = tuple.index(where: {($0.key == "price")}) {
    print(index)
}
//prints 1