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


I just whether is this possible to have an array of object MyObject, and the MyObject got a variable called isTrue, except from looping the whole array to check whether all the object in that array is true, is that any short hands to do so? Thanks.

Best Solution

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"