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

前端 未结 6 967
温柔的废话
温柔的废话 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:49

    You can use a predicate and check for equality:

    let tuples = [(1, 1), (0, 1)]
    
    let tuple1 = (1, 2)
    let tuple2 = (0, 1)
    
    if tuples.contains(where: {$0 == tuple1}) {
        print(true)
    } else {
        print(false)    // false
    }
    
    if tuples.contains(where: {$0 == tuple2}) {
        print(true)    // true
    } else {
        print(false)
    }
    

    You can also create your own contains methods that takes generic tuples:

    extension Sequence  {
        func contains(_ tuple: (T, U)) -> Bool where T: Equatable, U: Equatable, Element == (T,U) {
            contains { $0 == tuple }
        }
        func contains(_ tuple: (T, U, V)) -> Bool where T: Equatable, U: Equatable, V: Equatable, Element == (T,U,V) {
            contains { $0 == tuple }
        }
        func contains(_ tuple: (T, U, V, W)) -> Bool where T: Equatable, U: Equatable, V: Equatable, W: Equatable,Element == (T, U, V, W) {
            contains { $0 == tuple }
        }
        func contains(_ tuple: (T, U, V, W, X)) -> Bool where T: Equatable, U: Equatable, V: Equatable, W: Equatable, X: Equatable, Element == (T, U, V, W, X) {
            contains { $0 == tuple }
        }
        func contains(_ tuple: (T, U, V, W, X, Y)) -> Bool where T: Equatable, U: Equatable, V: Equatable, W: Equatable, X: Equatable, Y: Equatable, Element == (T, U, V, W, X, Y) {
            contains { $0 == tuple }
        }
    }
    

    if tuples.contains(tuple1) {
        print(true)
    } else {
        print(false)    // false
    }
    
    if tuples.contains(tuple2) {
        print(true)    // true
    } else {
        print(false)
    }
    

提交回复
热议问题