How do I check if an array of tuples contains a particular one in Swift?

前端 未结 6 966
温柔的废话
温柔的废话 2021-01-12 02:28

Consider the following Swift code.

var a = [(1, 1)]

if contains(a, (1, 2)) {
    println(\"Yes\")
}

All I need is to check if a

6条回答
  •  被撕碎了的回忆
    2021-01-12 02:50

    While tuples aren’t Equatable, you do not need to go so far as writing your own version of contains, since there is a version of contains that takes a matching predicate:

    if contains(a, { $0.0 == 1 && $0.1 == 2 }) {
         // a contained (1,2)
    }
    

    While you can’t extend tuples to be equatable, you can write a version of == for tuples, which would make the above code simpler:

    func ==(lhs: (T,U), rhs: (T,U)) -> Bool {
        return lhs.0 == rhs.0 && lhs.1 == rhs.1
    }
    
    contains(a) { $0 == (1,2) } // returns true
    

    It’d be nice to be able to write a version of contains for tuples, but alas, I don’t think the placeholder syntax supports it:

    EDIT: as of Swift 1.2, this does now compile as you can use tuples in placeholder constraints

    func contains
      
      (seq: S, x: (T,U)) -> Bool {
        return contains(seq) { $0.0 == x.0 && $0.1 == x.1 }
    }
    
    let a = [(1,1), (1,2)]
    
    if contains(a, (1,2)) {
        println("Yes")
    }
    

提交回复
热议问题