12

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!

Mike Nathas
  • 1,247
  • 2
  • 11
  • 29
  • Could you show the code that you've used to create the array? – ielyamani Mar 03 '19 at 20:00
  • The array ist just a list of dictionaries that are not created in the code but loaded from a file and a value for the non existing key "index" has to be added for each dictionary – Mike Nathas Mar 03 '19 at 20:02
  • Please edit you're question with any additional information that would make your problem easy to understand and reproduce in a playground – ielyamani Mar 03 '19 at 20:04
  • Added myArray in the original code so it can be reproduced – Mike Nathas Mar 03 '19 at 20:05

3 Answers3

17

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 }
ielyamani
  • 17,807
  • 10
  • 55
  • 90
1

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;
}]
E.Coms
  • 11,065
  • 2
  • 23
  • 35
0

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] }
Code Different
  • 90,614
  • 16
  • 144
  • 163