Why does the reverse() function in the Swift standard library return ReverseRandomAccessCollection?

前端 未结 3 489
野趣味
野趣味 2020-12-03 07:46

Now that I\'ve learned Swift (to a reasonable level) I\'m trying to get to grips with the standard library, but in truth it\'s mainly ελληνικά to me!

So a specific q

3条回答
  •  既然无缘
    2020-12-03 07:55

    It is an performance optimization for both time and memory. The ReverseRandomAccessCollection presents the elements of the original array in reverse order, without the need to create a new array and copying all elements (as long as the original array is not mutated).

    You can access the reversed elements with subscripts:

    let el0 = arr[arr.startIndex]
    let el2 = arr[arr.startIndex.advancedBy(2)]
    

    or

    for i in arr.indices {
        print(arr[i])
    }
    

    You can also create an array explicitly with

    let reversed = Array(["Mykonos", "Rhodes", "Naxos"].reversed())
    

    A dictionary is also a sequence of Key/Value pairs. In

    let dict = ["greek" : "swift sometimes", "notgreek" : "ruby for this example"].reverse()
    

    a completely different reversed() method is called:

    extension SequenceType {
        /// Return an `Array` containing the elements of `self` in reverse
        /// order.
        ///
        /// Complexity: O(N), where N is the length of `self`.
        @warn_unused_result
        public func reversed() -> [Self.Generator.Element]
    }
    

    The result is an array with the Key/Value pairs of the dictionary in reverse order. But this is of limited use because the order of the Key/Value pairs in a dictionary can be arbitrary.

提交回复
热议问题