2

I try to make reversed array, please consider following:

let arrValues : [MyStruct] = 
            [MyStruct(key: "id-5"),     
             MyStruct(key: "id-10"),
             MyStruct(key: "id-20")]

let reversedKeys = arrValues.map{$0.key ?? ""}.reversed()

it suppose to work, but in log i see keys in same order i did add them.

foundry
  • 31,615
  • 9
  • 90
  • 125
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • @the4kman yes, what is wrong with that – Evgeniy Kleban Dec 19 '17 at 13:41
  • 3
    Does the output look like this: `ReversedRandomAccessCollection>(_base: ["id-5", "id-10", "id-20"])`? Because that's expected; you're getting back a reversed *view* onto the mapped array, not a new reversed array. If you want a reversed array, then say `let reversedKeys: Array = arrValues.map{$0.key ?? ""}.reversed()`. – Hamish Dec 19 '17 at 13:43
  • 2
    Related: [Why does the reverse() function in the Swift standard library return ReverseRandomAccessCollection?](https://stackoverflow.com/questions/34558390/why-does-the-reverse-function-in-the-swift-standard-library-return-reverserand). – Martin R Dec 19 '17 at 13:44
  • @MartinR thanks, bookmarked – Evgeniy Kleban Dec 19 '17 at 13:45
  • @Hamish thanks, still i think this is kind of weird :) – Evgeniy Kleban Dec 19 '17 at 13:46
  • 1
    `arrValues.reversed().map{$0.key ?? ""}` should also produce an array. – Martin R Dec 19 '17 at 13:48
  • @MartinR what's the difference.. – Evgeniy Kleban Dec 19 '17 at 13:48
  • [`Sequence.map()`](https://developer.apple.com/documentation/swift/sequence/2905795-map) has an array as return type. – Martin R Dec 19 '17 at 13:50

1 Answers1

4

Well this is a easy test for the playground:

import UIKit

struct MyStruct {
    var key: String?
}

let arrValues : [MyStruct] = [MyStruct(key: "id-5"), MyStruct(key: "id-10"), MyStruct(key: "id-20")]

let reversedKeys = arrValues.map{$0.key ?? ""}.reversed()
for key in reversedKeys {
    debugPrint(key)
}

The debugPrint will show correctly: "id-20" "id-10" "id-5"

But if you stop the execution and debug the contents of reversedKeys it will show id-5 id-10 id-20

There are two functions reverse() and reversed().

reversed() doesn't actually reorder the array. It just returns an object (like an iterator) which iterates the elements from the end to the start. It has a complexity of O(1).

However reverse() changes the order of the elements, complexity of O(n). But it has to be a mutable array cause is a mutating function, so following the example you will need to do something like this:

var mutableCopy = arrValues
mutableCopy.reverse()
let reverseKeys = mutableCopy.map{$0.key ?? ""}
for key in reverseKeys {
    debugPrint(key)
}

If you just need to iterate the keys use reversed(), but if you have to access the keys with a subscript like reverseKeys[2], then you should use reverse()

LightMan
  • 3,517
  • 31
  • 31