What trouble could bring assining reversed() to a swift array?

前端 未结 1 1357
深忆病人
深忆病人 2021-01-25 08:32

I\'m wondering about the reversed() method on a swift Array:

var items = [\"a\", \"b\", \"c\"]

items = items.reversed()

the signature of the r

相关标签:
1条回答
  • 2021-01-25 08:46

    There are 3 overloads of reversed() for an Array in Swift 3:

    1. Treating the Array as a RandomAccessCollection,
      func reversed() -> ReversedRandomAccessCollection<Self> (O(1))
    2. Treating the Array as a BidirectionalCollection,
      func reversed() -> ReversedCollection<Self> (O(1))
    3. Treating the Array as a Sequence,
      func reversed() -> [Self.Iterator.Element] (O(n))

    By default, reversed() pick the RandomAccessCollection's overload and return a ReversedRandomAccessCollection. However, when you write

    items = items.reversed()
    

    you are forcing the RHS to return a type convertible to the LHS ([String]). Thus, only the 3rd overload that returns an array will be chosen.

    That overload will copy the whole sequence (thus O(n)), so there is no problem overwriting the original array.


    Instead of items = items.reversed(), which creates a copy of the array, reverse that and copy it back, you could reach the same effect using the mutating function items.reverse(), which does the reversion in-place without copying the array twice.

    0 讨论(0)
提交回复
热议问题