Is this possible to check all value in swift array is true instead of looping one by one?

edit/update: Swift 4.2 or later

Swift 4.2 introduced a new method called allSatisfy(_:)

let bools = [true,false,true,true]

if bools.allSatisfy({$0}) {
    print("all true")
} else {
    print("contains false") // "contains false\n"
}

Swift 5.2 we can also use a KeyPath property

class Object {
    let isTrue: Bool
    init(_ isTrue: Bool) {
        self.isTrue = isTrue
    }
}

let obj1 = Object(true)
let obj2 = Object(false)
let obj3 = Object(true)

let objects = [obj1,obj2,obj3]

if objects.allSatisfy(\.isTrue) {
    print("all true")
} else {
    print("not all true")  // "not all true\n"
}


As of Xcode 10 and Swift 4.2 you can now use allSatisfy(_:) with a predicate:

let conditions = [true, true, true]
if conditions.allSatisfy({$0}) {
  // Do stuff
}

A purely functional way using reduce function:

let boolArray = [true,true,true,true]
let isAllTrue = boolArray.reduce(true, combine: {$0 && $1}) // true

Tags:

Arrays

Swift