Swayambhu Swayambhu - 2 years ago 156
Swift Question

How to find the index of a tuple element from an tuple array? iOS, Swift

This is inside tableview cellforrowatindexpath

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

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?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download