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
From the language docs of ReverseCollention (result of .reverse()
):
The reverse() method is always lazy when applied to a collection with bidirectional indices, but does not implicitly confer laziness on algorithms applied to its result.
In other words, for ordinary collections c having bidirectional indices:
- c.reverse() does not create new storage
...
Hence, you could see your ReverseRandomAccessCollection
as a random access wrapper over your not yet reversed array (i.e., your original array arr
has not yet been copied and reversed to a new position in memory).
Naturally, from the above, you can't index the reverse collection directly, as an Array
gives access as a pointer to the memory that holds the array, and indexing corresponds to proceeding bitwise (depending on type) forward in memory. We can still, however, access the elements of the "reverse array" in array index style using ReverseRandomAccessIndex
:
let arr = ["Mykonos", "Rhodes", "Naxos"]
let arrReverse = arr.reverse()
/* ReverseRandomAccessCollection access "wrapper" over
the 'arr' data in memory. No new storage allocated */
let myIndex = arrReverse.startIndex.advancedBy(2)
/* bIndex type:
ReverseRandomAccessIndex> */
print(arrReverse[myIndex]) // "Mykonos"
Conversely, we can explicitly allocate memory for our reverse array, and treat it just as any other array. At this point, the arrReverse
is a separate array than arr
, and holds no relation to the former other than (once) being created by using it.
let arr = ["Mykonos", "Rhodes", "Naxos"]
let arrReverse = Array(arr.reverse())
/* Array */
let myIndex = arrReverse.startIndex.advancedBy(2)
/* bIndex type: Int */
print(arrReverse[myIndex]) // "Mykonos"
Martin R beat me to it, so see his note regarding the dictionaries.