Does Swift have a short circuit to higher-order functions such as Any or All?

I know about higher order quick functions like Map, Filter, Reduce and FlatMap, but I don't know anyone like โ€œAllโ€ or โ€œAnyโ€ that return a boolean that short circuit on a positive test listing the results.

For example, consider that you have a collection of 10,000 objects, each of which has a property with a name isFulfilled, and you want to see if this collection is set isFulfilledto false. In C #, you could use myObjects.Any(obj -> !obj.isFulfilled), and when this condition was removed, it shorted the rest of the enumeration and returned immediately true.

Is there such a thing in Swift?

+4
source share
3 answers

Sequence(and in particular Collectionand Array) has a (short-circuited) contains(where:)method that takes boolean predicate as an argument. For instance,

if array.contains(where: { $0 % 2 == 0 })

checks if the array contains any even number.

There is no โ€œallโ€ method, but you can use contains()as well as denying both the predicate and the result. For instance,

if !array.contains(where: { $0 % 2 != 0 })

checks if all numbers in the array are even. Of course, you can define your own extension method:

extension Sequence {
    func allSatisfy(_ predicate: (Iterator.Element) -> Bool) -> Bool {
        return !contains(where: { !predicate($0) } )
    }
}

If you want to allow predicate throwing in the same way as contains, then it will be defined as

extension Sequence {
    func allSatisfy(_ predicate: (Iterator.Element) throws -> Bool) rethrows -> Bool {
        return try !contains(where: { try !predicate($0) } )
    }
}
+3
source

, Swift, " " , lazy , - :

myObjects.lazy.filter({ !$0.isFulfilled }).first != nil

, , . lazy Apple. :

var lazy: LazyCollection > , .

var lazy: LazySequence > , , , , .

+3

, , isFulfilled..., , confrom ( fullFilled)... [FulfilledItem]... , ,

:

, Any AnyObject, AnyObject ( Apple, ), " " - AnyObject...

 protocol FulfilledItem: AnyObject{

    var isFulfilled: Bool {get set}

}

class itemWithTrueValue: FulfilledItem{
    var isFulfilled: Bool = true
}

class itemWithFalseValue: FulfilledItem{
    var isFulfilled: Bool = false
}

var arrayOfFulFilled: [FulfilledItem] = [itemWithFalseValue(),itemWithFalseValue(),itemWithFalseValue(),itemWithFalseValue(),itemWithFalseValue(),itemWithFalseValue()]

  let boolValue =   arrayOfFulFilled.contains(where: {
       $0.isFulfilled == false
    })

, Any + isFulfilled , , ...

:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-ID342

AnyObject (), Any - , , , AnyObject...

AnyObject Array Item FulfilledItem, ( , ...)

:)

0
source

Source: https://habr.com/ru/post/1678442/


All Articles