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

Swa*_*bhu 3 arrays tuples ios swift

这是在tableview cellforrowatindexpath中

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

这是在didselectrowatIndexPath里面

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

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

Mar*_*n R 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)
}
Run Code Online (Sandbox Code Playgroud)

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

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


Bat*_*Can 5

这是我查找元组索引的选项

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
Run Code Online (Sandbox Code Playgroud)