I've found the .contains(Element) method pretty essential in my minimal experience writing Swift code, and have quickly realized that Apple changed it...
func contains(check:[[[Int]]], forElement: [[Int]]) -> Bool {
for element in check {
if areEqual(element, forElement) {
return true
}
}
return false
}
func areEqual(_ a:[[Int]], _ b:[[Int]]) -> Bool {
for i in 0..<a.count {
if a[i] != b[i] {
return false
}
}
return true
}
I've been messing with some large arrays, so I fixed my problem with that clunky function.
What happened?
How do you use the new way?
The example there is well over my head.
enum HTTPResponse {
case ok
case error(Int)
}
let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
if case .error = element {
return true
} else {
return false
}
}
// 'hadError' == true
To check if an element is in an array in Swift, use the Array. contains() function.
To do this task we use the contains() function. This function is used to check if the given element is present or not in the specified array. It will return true if the given value is present in the array otherwise it will return false.
The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.
It's easy to find out whether an array contains a specific value, because Swift has a contains() method that returns true or false depending on whether that item is found. For example: let array = ["Apples", "Peaches", "Plums"] if array.
How about using this
let numbers = [1, 2, 3, 4]
let contains = numbers.contains(where: { $0 == 3 })
//contains == true
Or
let strings = ["A", "B", "C", "D"]
let contains = strings.contains(where: { $0 == "B" })
//contains == true
Even with other objects like NSColor
let colors: [NSColor] = [.red, .blue, .green]
contains = colors.contains(where: { $0 == .red })
//contains == true
That API just lets you pass a block where you can perform any checks you want. You can check whether the given element is equal to something, or whether its properties satisfy some constraints (such as in the example in the documentation). You should be able to perform a basic equality check like this:
func contains(check:[[[Int]]], forElement: [[Int]]) -> Bool {
return check.contains { element in
return areEqual(element, forElement)
}
}
func areEqual(_ a:[[Int]], _ b:[[Int]]) -> Bool {
for i in 0..<a.count {
if a[i] != b[i] {
return false
}
}
return true
}
The contains block iterates over every element and returns either true
or false
. In the end, a single true
for any element will return true
for the whole function.
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