Swift高階函數-contains、allSatisfy、reversed、lexicographicallyPrecedes

一、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
    }
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章