Hannibal
Hannibal

Reputation: 9

Array that the elements are tuples, how can I check an index?

here's an array that the elements are tuples. And I want to check the elements index by using firstIndex(of:)

var f: [(String, String)] = [
    ("a", "a"),
    ("b", "b"),
    ("0", "c"),
    ("d", "d"),
    ("e", "e")
]

var x = f[0]
f.firstIndex(of: x) // error: Type '(String, String)' cannot conform to 'Equatable'
f.firstIndex(of: ("a", "a")) // error: Type '(String, String)' cannot conform to 'Equatable'

I tried to find a reason why the error happens, but could not. Can anybody tell me the reason...?

Searched on google and stack overflow... but couldn't

Upvotes: 0

Views: 75

Answers (2)

yonivav
yonivav

Reputation: 1033

Why do you use firstIndex?

Try using .0 and .1:

var f: [(String, String)] = [
    ("a", "a"),
    ("b", "b"),
    ("0", "c"),
    ("d", "d"),
    ("e", "e")
]
var x = f[0]
print(x.0) // prints "a"
print(f[2].0) // prints "0"
print(f[2].1) // prints "c"

Upvotes: 0

Taron Qalashyan
Taron Qalashyan

Reputation: 723

You can create a custom Equatable conformance for the (String, String) tuple type.

extension (String, String): Equatable {
    static func == (lhs: (String, String), rhs: (String, String)) -> Bool {
        return lhs.0 == rhs.0 && lhs.1 == rhs.1
    }
}

Upvotes: 1

Related Questions