问题
This is inside tableview cellforrowatindexpath
var valueArray:[(String,String)] = []
if !contains(valueArray, v: (title,status)) {
let v = (title,status)
valueArray.append(v)
}
This is inside didselectrowatIndexPath
let cell = self.tableView.cellForRowAtIndexPath(selectedRow!)
var newTuple = (cell!.textLabel!.text!, cell!.detailTextLabel!.text!)
let index = valueArray.indexOf(newTuple)
But i am not getting the index. It is throwing an error cannot convert value of type '(String,String)' to expected argument type '@noescape ((String,String)) throws -> Bool'. What i am doing wrong here?
回答1:
Tuples can be compared for equality (as of Swift 2.2/Xcode 7.3.1), but
they do not conform to the Equatable
protocol. Therefore you have
to use the predicate-based variant of indexOf
to locate a tuple
in an array. Example:
let valueArray = [("a", "b"), ("c", "d")]
let tuple = ("c", "d")
if let index = valueArray.indexOf({ $0 == tuple }) {
print("found at index", index)
}
In Swift 4 the method has been renamed to firstIndex(where:)
:
if let index = valueArray.firstIndex(where: { $0 == tuple }) {
print("found at index", index)
}
回答2:
Here is my option to find index of tuples
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
来源:https://stackoverflow.com/questions/37904601/how-to-find-the-index-of-a-tuple-element-from-an-tuple-array-ios-swift