Consider the following Swift code.
var a = [(1, 1)]
if contains(a, (1, 2)) {
println(\"Yes\")
}
All I need is to check if a
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)
}