Evgenii
Evgenii

Reputation: 37339

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

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?

Upvotes: 20

Views: 10647

Answers (4)

Abdullah
Abdullah

Reputation: 393

this may help

func find(value coinSymbol: String, in array: [CoinModel]) -> CoinModel? {
    for (_, value) in array.enumerated() {
        if value.symbol.uppercased() == coinSymbol {
            return value
        }
    }
    return nil
}

Upvotes: -3

Leo Dabus
Leo Dabus

Reputation: 236458

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)
}

Upvotes: 29

Sarp Başaraner
Sarp Başaraner

Reputation: 516

Correct answer updated for Swift 5:

[1, 2, 3].contains(where: { $0 % 2 == 0 })

Upvotes: 10

Roman Podymov
Roman Podymov

Reputation: 4521

In Swift 4.2/Xcode 10 you can use the method allSatisfy of class Array to solve your problem. Here is an example:

let a = !([1, 2, 3].allSatisfy { $0 % 2 != 0 })
print(a) // true
let b = !([1, 3, 5].allSatisfy { $0 % 2 != 0 })
print(b) // false

If your current version of Xcode is prior to 10.0 you can find the function allSatisfy in Xcode9to10Preparation. You can install this library with CocoaPods.

Upvotes: 0

Related Questions