1

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

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

items = items.reversed()

the signature of the reversed method from the Apple doc says that it returns a

ReversedRandomAccessCollection<Array<Element>>

could that be assigned back to items without doing what the apple doc say which is

For example, to get the reversed version of an array, initialize a new Array instance from the result of this reversed() method.

or would it give problem in the future? (since the compiler doesn't complain)

Massimo
  • 159
  • 1
  • 10

1 Answers1

9

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))

Protocols conformed by Array

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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    Good Explanation. Allow me to make your last note more clear for viewers that they are not familiar with "mutating", by mentioning that `reversed()` returns a new separated copy of the array which will be reserved, but `reserve()` will affect (reserve) the array itself, without returning a new copy. – Ahmad F Mar 09 '17 at 07:47
  • @AhmadF. Thanks. Inserted some explanation into the answer. – kennytm Mar 09 '17 at 07:49
  • That's even better! Thank you for your time and consideration :) – Ahmad F Mar 09 '17 at 07:52
  • @ahmad s/reserve/reverse/g – David Berry Mar 09 '17 at 19:43