List through an array of structures

Take a look at this code:

struct Person { var name: String var age: Int } var array = [Person(name: "John", age: 10), Person(name: "Apple", age: 20), Person(name: "Seed", age: 30)] //for item in array { item.name = "error: cannot assign to property: 'item' is a 'let' constant" } array[0].name = "Javert" //work fine. 

I am trying to change the value of a structure property inside a loop.

Of course, I can change Person to class , and it works fine. However, I do not understand why item is le .

Oh, I just figured it out, for item in... just created the copied actual object inside the array , this means that it is automatically declared by the let constant.

So why can't I change the value of its property.

My question is: besides changing Person to class , how to change Person properties inside a loop?


Edit:

Thanks @Zoff Dino with the original answers for index in 0..<array.count .

However, this is just a simplified question.

I want to archive using higher order functions with an array of structures, for example:

array.each { item in ... }.map { item in ... }.sort { } ...

+4
source share
2 answers

The old school for i in ... will do the job perfectly:

 for i in 0..<array.count { array[i].name = "..." } 

Edit : The higher order function you were talking about? This will sort the array in descending order of age :

 var newArray = array.map { Person(name: "Someone", age: $0.age) }.sort { $0.age > $1.age } print(newArray) 
+3
source

If you want to change some properties of the elements, you can use map and return its mutated copy:

 array.map{ person -> Person in var tempPerson = person tempPerson.name = "name" return tempPerson }.sort{ ... } 
+1
source

All Articles