I need to change values of a Swift array. My first try was to just iterate through but this does not work as I only get a copy of each element and the changes do not affect the origin array. Goal is to have a unique "index" in each array element.
myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
counter = 0
for item in myArray {
item["index"] = counter
counter += 1
}
My next attempt was using map but I don't know how to set an increasing value. I could set the $0["index"] = 1 but I need an increasing value.
In which way would this be possible using map?
myArray.map( { $0["index"] = ...? } )
Thanks for any help!
The counter in a for loop is a constant. To make it mutable, you could use :
for var item in myArray { ... }
But that won't be helpful here since we'd be mutating item and not the elements in myArray.
You could mutate the elements in myArray this way :
var myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
var counter = 0
for i in myArray.indices {
myArray[i]["index"] = counter
counter += 1
}
print(myArray) //[["index": 0], ["index": 1], ["index": 2], ["index": 3]]
The counter variable is not needed here :
for i in myArray.indices {
myArray[i]["index"] = i
}
A functional way of writing the above would be :
myArray.indices.forEach { myArray[$0]["index"] = $0 }
I found a simple way and would like to share it.
The key is the definition of myArray. It would success if it's in this way:
let myArray : [NSMutableDictionary] = [["firstDict":1, "otherKey":1], ["secondDict":2, "otherKey":1], ["lastDict":2, "otherKey":1]]
myArray.enumerated().forEach{$0.element["index"] = $0.offset}
print(myArray)
[{
firstDict = 1;
index = 0;
otherKey = 1;
}, {
index = 1;
otherKey = 1;
secondDict = 2;
}, {
index = 2;
lastDict = 2;
otherKey = 1;
}]
How about a more functional approach by creating a brand new array to store the modified dictionaries:
let myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
let myNewArray = myArray.enumerated().map { index, _ in ["index": index] }