Pham Hoan Pham Hoan - 6 months ago 18
Swift Question

Enumerate through array of structs

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'm trying to change property's value of a struct inside a loop.

Of course I can change
Person
to
class
and it works just fine. However, I don't understand why
item
is a
le
.

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

So that's why I cannot change its properties value.

My question is, beside changing
Person
to
class
, how can I change
Person
's properties inside a loop ?




Edit:

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

However, this is just a simplified question.

What I want to archive is using higher-order functions with array of structs, like:

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

Answer

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

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

Edit: higher order function you said? This will sort the array descendingly based on age:

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

print(newArray)