Search code examples
iosswiftcomparison-operators

Compare multiple variables to the same expression


I am trying to compare multiple variables to an expression, like so:

if 1 <= x && x <= 5 &&
    1 <= y && y <= 5 &&
    1 <= z && z <= 5 {
    // Code to run if true
}

I found a question related to comparing a variable to multiple specific values, which is not what I want because it is not a comparison in an inequality.

Is there any way I can shorten this, in any way?

For example making an inequality like 1 <= x && x <= 5 shortened, or making me able to compare x, y, and z easily in other ways?


Solution

  • Use ranges!

    if (1...5).contains(x) &&
       (1...5).contains(y) &&
       (1...5).contains(z) {
    
    }
    

    Alternatively, create a closure that checks whether something is in range:

    let inRange: (Int) -> Bool = (1...5).contains
    if inRange(x) && inRange(y) && inRange(z) {
    
    }
    

    As Hamish has suggested, the allSatisfy method in Swift 4.2 can be implemented as an extension like this:

    extension Sequence {
        func allSatisfy(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
            return try !contains { try !predicate($0) }
        }
    }