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.
Swift has built-in way of checking whether all items in an array match a condition: the allSatisfy() method. Give this thing a condition to check, and it will apply that condition on all items until it finds one that fails, at which point it will return false.
To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements. Copied!
To check if an element is in an array in Swift, use the Array. contains() function.
Array is faster than set in terms of initialization. Set is slower than an array in terms of initialization because it uses a hash process. The array allows to store duplicate elements in it. Set doesn't allow to store duplicate elements in it.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With