Consider the following Swift code.
var a = [(1, 1)]
if contains(a, (1, 2)) {
println("Yes")
}
All I need is to check if a
contains the tuple but the code leads to error.
Cannot find an overload for 'contains' that accepts an argument list of type '([(Int, Int)], (Int, Int))'
Why so and how to use contains
properly?
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<T, U>(_ tuple: (T, U)) -> Bool where T: Equatable, U: Equatable, Element == (T,U) {
contains { $0 == tuple }
}
func contains<T, U, V>(_ tuple: (T, U, V)) -> Bool where T: Equatable, U: Equatable, V: Equatable, Element == (T,U,V) {
contains { $0 == tuple }
}
func contains<T, U, V, W>(_ 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<T, U, V, W, X>(_ 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<T, U, V, W, X, Y>(_ 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With