4

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?

5
  • I think your issue is Swift doesn't know how to natively compare your tuple for equality. Look here: stackoverflow.com/questions/24487519/… Commented Jun 19, 2016 at 6:39
  • 1
    Don't store tuples in arrays. Create a struct or object. And yes, you need to consider the test of equality Commented Jun 19, 2016 at 6:52
  • Also, why isn't valueArray(selectedRow) the one you are after? Commented Jun 19, 2016 at 6:55
  • @Paulw11 didnot get you. Commented Jun 19, 2016 at 9:59
  • @sschale yeah i know the issue, thats why trying to find a solution Commented Jun 19, 2016 at 9:59

2 Answers 2

17

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

actually it can also work like contains function if we use an else statement ;)
6

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.