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

Time:01-18

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

CodePudding user response:

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
    }
}

CodePudding user response:

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"
  • Related