首页 > 随笔 > Swift高阶函数-contains、allSatisfy、reversed、lexicographicallyPrecedes

Swift高阶函数-contains、allSatisfy、reversed、lexicographicallyPrecedes

简书 2026-10-06 03:10 4 阅读 查看原文

一、contains

返回一个布尔值,指示序列的每个元素是否满足给定的条件。如果有一个满足即返回。

 let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41] let hasBigPurchase = expenses.contains { $0 > 100 } // 'hasBigPurchase' == true 

Sequence协议源码

 @inlinable public func contains(_ element: Element) -> Bool { if let result = _customContainsEquatableElement(element) { return result } else { return self.contains { $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 } 

二、allSatisfy

返回一个布尔值,指示序列的每个元素是否满足给定的条件。需要所有元素都满足。

 let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 }) // allHaveAtLeastFive == true 

Sequence协议源码
allSatisfy里面调用了contains方法

 @inlinable public func allSatisfy( _ predicate: (Element) throws -> Bool ) rethrows -> Bool { return try !contains { try !predicate($0) } } 

三、reversed

返回一个数组,该数组以相反的顺序包含此序列的元素。

let list = [1, 2, 3, 4, 5] let ret = list.reversed() print(Array(ret)) ---console [5, 4, 3, 2, 1] 

Sequence协议源码

 @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 = result.count for i in 0..<count/2 { result.swapAt(i, count - ((i + 1) as Int)) } return result } 

四、lexicographicallyPrecedes

返回一个布尔值,该值指示在字典顺序(字典)中该序列是否在另一个序列之前,使用给定条件语句比较元素。

let list = [1, 2, 3, 4, 5] let list2 = [2, 2, 3, 5] let ret1 = list.lexicographicallyPrecedes(list2) let ret2 = list2.lexicographicallyPrecedes(list) print(ret1, ret2) ---console true false 

Sequence协议源码

 @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence ) -> Bool where OtherSequence.Element == Element { return self.lexicographicallyPrecedes(other, by: <) } 
 @inlinable public func lexicographicallyPrecedes<OtherSequence: Sequence>( _ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> Bool where OtherSequence.Element == Element { var iter1 = self.makeIterator() var iter2 = other.makeIterator() while true { if let e1 = iter1.next() { if let e2 = iter2.next() { if try areInIncreasingOrder(e1, e2) { return true } if try areInIncreasingOrder(e2, e1) { return false } continue // Equivalent } return false } return iter2.next() != nil } }