Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Swift array and change values

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!

like image 260
Mike Nathas Avatar asked Mar 03 '19 19:03

Mike Nathas


1 Answers

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 }
like image 186
ielyamani Avatar answered Oct 17 '22 08:10

ielyamani