Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

Swift reverse array not working

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.

Upvotes: 2

Views: 2334

Answers (1)

LightMan
LightMan

Reputation: 3575

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

Upvotes: 4

Related Questions