ios swift Sequence 协议方法

65 阅读2分钟

ios swift 进阶 - 基础原理探索 合集- 荔枝

查看合集juejin.cn/post/729867…

WechatIMG586.png

1. 搅乱,洗牌 func shuffled(using generator: inout T)

官方说明

image.png

       let numbers = 0...9

        let shuffledNumbers = numbers.shuffled()

        // shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]

3. 展平映射func flatMap(_ transform: (Base.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

flatMap 方法首先会对集合中的每一个元素应用一个变换函数,然后将所有结果“展平”到一个新的集合中。

  • 可将集合中的所有集合取出,最终变成一个新的集合

示例:

let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flatNumbers = nestedNumbers.flatMap { $0 }
print(flatNumbers) // 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]

在这个例子中,flatMap 首先应用变换函数,将每个子数组提取出来,然后将所有子数组展平为一个单一的数组。

处理可选类型(Optional)

flatMap 在处理可选类型时非常有用,它会自动解包可选值并过滤掉 nil 值,而 map 则会保留 nil。

示例:

let numbers: [Int?] = [1, 2, nil, 4, nil, 5]
let mappedNumbers = numbers.map { $0 }
print(mappedNumbers) // 输出: [Optional(1), Optional(2), nil, Optional(4), nil, Optional(5)]

let flatMappedNumbers = numbers.flatMap { $0 }
print(flatMappedNumbers) // 输出: [1, 2, 4, 5]

在这个例子中,flatMap 会解包可选值并移除 nil 值,而 map 会保留 nil 值。

参考:blog.csdn.net/qfeung/arti…

image.png

4. 映射 func map(_ transform: (Self.Element) throws -> T) rethrows -> [T]

官方定义

image.png

代码示例

   let cast = ["Vivien", "Marlon", "Kim", "Karl"]
    let lowercaseNames = cast.map { $0.lowercased() }
     // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
    let letterCounts = cast.map { $0.count }
    // 'letterCounts' == [6, 6, 3, 4]

5 过滤 public func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

官方定义

image.png

6. 遍历 func forEach(_ body: (Self.Element) throws -> Void) rethrows

官方定义

image.png

7. 第一个 func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?

image.png

8. 拆分 func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [ArraySlice<Self.Element>]

image.png

9. 后缀 func suffix(_ maxLength: Int) -> [Self.Element]

image.png

10.丢弃前面几位 func dropFirst(_ k: Int = 1) -> DropFirstSequence

image.png

11. 丢弃后几位 func dropLast(_ k: Int = 1) -> [Self.Element]

image.png

12. 条件丢弃 func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> DropWhileSequence

image.png

13. 前缀 func prefix(_ maxLength: Int) -> PrefixSequence

image.png

14. 条件选择 前缀 func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> [Self.Element]

image.png

15. 元素枚举 func enumerated() -> EnumeratedSequence

image.png

16. 最小元素 func min(by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool) rethrows -> Base.Element?

image.png

17. 最大元素 func max(by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool) rethrows -> Base.Element?

image.png

18. 序列的初始元素是否与另一个序列中的元素相同 func starts(with possiblePrefix: PossiblePrefix, by areEquivalent: (Base.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool where PossiblePrefix : Sequence

官方定义

image.png

代码示例

此示例测试一个可数范围是否以另一个可数范围的元素开始。

 let a = 1...3 
 let b = 1...10 
 print(b.starts(with: a)) 
  // Prints "true"
19. 元素相等 func elementsEqual(_ other: OtherSequence, by areEquivalent: (Base.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence

官方定义 image.png

示例代码

let list = [1, 2, 3, 4, 5]
let list2 = [1, 4, 9, 16, 25]

let ret1 = list.elementsEqual(list2)
let ret2 = list.elementsEqual(list2) { el, seEl in
    return el * el == seEl
}
print(ret1, ret2)
---console
false true
20. 小于操作符(<)比较元素 返回一个布尔值,该值指示在字典顺序(字典)中该序列是否在另一个序列之前 func lexicographicallyPrecedes(_ other: OtherSequence, by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool) rethrows -> Bool where OtherSequence : Sequence, Base.Element == OtherSequence.Element

image.png

示例代码

  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
21. 是否条件包含 func contains(where predicate: (Base.Element) throws -> Bool) rethrows -> Bool

image.png

22. 是否所有元素满足 func allSatisfy(_ predicate: (Base.Element) throws -> Bool) rethrows -> Bool

image.png

23. 累加,合并 func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

image.png

24. 遍历累加,合并到另一个对象中func reduce(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result

image.png

25. 反转 func reversed() -> [Base.Element]

image.png

27. 压缩映射 func compactMap(_ transform: (Base.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]

  • 当集合中有nil存在时使用CompactMap函数

image.png

28. 排序func sorted(by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool) rethrows -> [Base.Element]

官方定义

 /// Returns the elements of the sequence, sorted using the given predicate as
    /// the comparison between elements.
    ///
    /// When you want to sort a sequence of elements that don't conform to the
    /// `Comparable` protocol, pass a predicate to this method that returns
    /// `true` when the first element should be ordered before the second. The
    /// elements of the resulting array are ordered according to the given
    /// predicate.
    ///
    /// In the following example, the predicate provides an ordering for an array
    /// of a custom `HTTPResponse` type. The predicate orders errors before
    /// successes and sorts the error responses by their error code.
    ///
    ///     enum HTTPResponse {
    ///         case ok
    ///         case error(Int)
    ///     }
    ///
    ///     let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
    ///     let sortedResponses = responses.sorted {
    ///         switch ($0, $1) {
    ///         // Order errors by code
    ///         case let (.error(aCode), .error(bCode)):
    ///             return aCode < bCode
    ///
    ///         // All successes are equivalent, so none is before any other
    ///         case (.ok, .ok): return false
    ///
    ///         // Order errors before successes
    ///         case (.error, .ok): return true
    ///         case (.ok, .error): return false
    ///         }
    ///     }
    ///     print(sortedResponses)
    ///     // Prints "[.error(403), .error(404), .error(500), .ok, .ok]"
    ///
    /// You also use this method to sort elements that conform to the
    /// `Comparable` protocol in descending order. To sort your sequence in
    /// descending order, pass the greater-than operator (`>`) as the
    /// `areInIncreasingOrder` parameter.
    ///
    ///     let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
    ///     let descendingStudents = students.sorted(by: >)
    ///     print(descendingStudents)
    ///     // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"
    ///
    /// Calling the related `sorted()` method is equivalent to calling this
    /// method and passing the less-than operator (`<`) as the predicate.
    ///
    ///     print(students.sorted())
    ///     // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
    ///     print(students.sorted(by: <))
    ///     // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
    ///
    /// The predicate must be a **strict weak ordering** over the elements. That
    /// is, for any elements `a`, `b`, and `c`, the following conditions must
    /// hold:
    ///
    /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
    /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
    ///   both `true`, then `areInIncreasingOrder(a, c)` is also `true`.
    ///   (Transitive comparability)
    /// - Two elements are **incomparable** if neither is ordered before the other
    ///   according to the predicate. If `a` and `b` are incomparable, and `b`
    ///   and `c` are incomparable, then `a` and `c` are also incomparable.
    ///   (Transitive incomparability)
    ///
    /// The sorting algorithm is guaranteed to be stable. A stable sort
    /// preserves the relative order of elements for which
    /// `areInIncreasingOrder` does not establish an order.
    ///
    /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
    ///   first argument should be ordered before its second argument;
    ///   otherwise, `false`.
    /// - Returns: A sorted array of the sequence's elements.
    ///
    /// - Complexity: O(**n** log **n**), where **n** is the length of the sequence.

    @inlinable public func sorted(by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool) rethrows -> [Base.Element]

29 加入 func joined() -> FlattenSequence

image.png

30. 加入分割 func joined(separator: Separator) -> JoinedSequence where Separator : Sequence, Separator.Element == Self.Element.Element

image.png