How to check if any of the items satisfy certain criteria in Swift collection?
Correct answer updated for Swift 5:
[1, 2, 3].contains(where: { $0 % 2 == 0 })
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)
}