1. contains
Returns a Boolean value indicating whether each element of the sequence satisfies the given condition. If one is satisfied, it will return.
let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] let hasBigPurchase = { $0 > 100 } // 'hasBigPurchase' == true
Sequence
Protocol source code
@inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return { $0 == element } } }
@inlinable public func contains( where predicate: (Element) throws -> Bool ) rethrows -> Bool { for e in self { if try predicate(e) { return true } } return false }
2. allSatisfy
Returns a Boolean value indicating whether each element of the sequence satisfies the given condition. All elements need to be satisfied.
let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] let allHaveAtLeastFive = ({ $ >= 5 }) // allHaveAtLeastFive == true
Sequence
Protocol source code
allSatisfy
Called insidecontains
method
@inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } }
3. reversed
Returns an array containing the elements of this sequence in reverse order.
let list = [1, 2, 3, 4, 5] let ret = () print(Array(ret)) ---console [5, 4, 3, 2, 1]
Sequence
Protocol source code
@inlinable public __consuming func reversed() -> [Element] { // FIXME(performance): optimize to 1 pass? But Array(self) can be // optimized to a memcpy() sometimes. Those cases are usually collections, // though. var result = Array(self) let count = for i in 0..<count/2 { (i, count - ((i + 1) as Int)) } return result }
4. Lexicographically Precedes
Returns a Boolean value indicating whether the sequence is before another sequence in dictionary order (dictionary) and the elements are compared using the given conditional statement.
let list = [1, 2, 3, 4, 5] let list2 = [2, 2, 3, 5] let ret1 = (list2) let ret2 = (list) print(ret1, ret2) ---console true false
Sequence
Protocol source code
@inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where == Element { return (other, by: <) }
@inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where == Element { var iter1 = () var iter2 = () while true { if let e1 = () { if let e2 = () { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return () != nil } }
The above is the detailed content of the usage example of Swift higher-order functions contains allSatisfy reversed lexicographicallyPrecedes. For more information on the usage of Swift higher-order functions, please pay attention to my other related articles!