Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if any of the items satisfy certain criteria in Swift collection?

Tags:

swift

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

My imperfect solution

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.

  1. It is a bit verbose.

  2. The filter closure argument will be called for all items in the array, which is unnecessary.

Is there a better way of doing it?

like image 897
Evgenii Avatar asked Jun 21 '15 05:06

Evgenii


1 Answers

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)
}
like image 178
Leo Dabus Avatar answered Nov 15 '22 15:11

Leo Dabus