Is there a way in Swift to check if any of the items satisfy certain criteria?
For example, given an array of integers I would like to see if it contains even numbers (this code will not work):
[1, 2, 3].any { $0 % 2 == 0 } // true
[1, 3, 5].any { $0 % 2 == 0 } // false
I am currently using the following approach:
let any = [1, 3, 5].filter { $0 % 2 == 0 }.count > 0
I don't think it is very good.
It is a bit verbose.
The filter closure argument will be called for all items in the array, which is unnecessary.
Is there a better way of doing it?
You can use the method contains
to accomplish what you want. It is better than filter because it does not need a whole iteration of the array elements:
let numbers = [1, 2, 3]
if numbers.contains(where: { $0 % 2 == 0 }) {
print(true)
}
or Xcode 10.2+ https://developer.apple.com/documentation/swift/int/3127688-ismultiple
if numbers.contains(where: { $0.isMultiple(of: 2) }) {
print(true)
}
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