Sean
Sean

Reputation: 721

Trying to understand map function for collection of structs

Please can someone explain the following code like I'm 5. I know what it's doing, changing all isLocked Bools to true in a struct array of type Person. I'm just having trouble with "storytelling" the syntax to myself.

people = people.map({
        (p) -> Person in
        var mod = p
        mod.isLocked = true
        return mod
})

Thanks.

Upvotes: 0

Views: 55

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17050

map lets you make a new array from an existing one by applying some transform closure to all of its elements. Unfortunately, in this example, your closure is returning the same elements that it takes, so if your Person is a class (rather than a struct), the map is completely unnecessary, and the code above will simply do the same thing as:

people.forEach { $0.isLocked = true }

If Person were a struct instead of a class, OTOH, then the map would have meaning, because you'd need to make a copy of each of the objects in order to modify it.

In the case of a struct, the map creates a new array consisting of copies of each Person struct in the array, with each copying having its isLocked property set to true:

people = people.map {
    (p) -> Person in
    var mod = p // make a copy of each Person, store it in 'mod'
    mod.isLocked = true // change the isLocked property of the copy to true
    return mod // return the modified copy
}

Upvotes: 3

Related Questions