4

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 { } ...

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Ya, thank you, I forgot that :D But 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 { } ...
2

If you only want to change some properties of the elements you can use map and return a mutated copy of it:

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

2 Comments

@PhamHoan Considering performance I should be very efficient since structs/value types can be copied very fast. A slightly more efficient version would be a for in loop over the indices and mutate the elements directly because no additional array has to be created. So for small arrays I wouldn't consider performance too much.
@adnako Thank you. I've updated my solution. The reason was that Swift 2.2 disallows var parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.