热点新闻
Swift高阶函数-contains、allSatisfy、reversed、lexicographicallyPrecedes
2023-07-05 01:39  浏览:634  搜索引擎搜索“错改B2B”
温馨提示:信息一旦丢失不一定找得到,请务必收藏信息以备急用!本站所有信息均是注册会员发布如遇到侵权请联系文章中的联系方式或客服删除!
联系我时,请说明是在错改B2B看到的信息,谢谢。
展会发布 展会网站大全 报名观展合作 软文发布

一、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 } }

发布人:d475****    IP:117.173.23.***     举报/删稿
展会推荐
让朕来说2句
评论
收藏
点赞
转发