Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

swift

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.

like image 964
DNB5brims Avatar asked May 28 '15 04:05

DNB5brims


People also ask

How do you check if all elements in an array are true Swift?

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.

How do you know if an array is true?

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!

Which property that used to check an array has items in Swift?

To check if an element is in an array in Swift, use the Array. contains() function.

Which one is faster array or set in Swift?

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.


2 Answers

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

like image 58
Leo Dabus Avatar answered Sep 23 '22 11:09

Leo Dabus


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 } 
like image 35
bangerang Avatar answered Sep 19 '22 11:09

bangerang