(The following is the case when Gnome
is a reference type, the class is because you did not show us how you defined Gnome
. In the case where Gnome
is a value type (structure), see @vadian: s answer)
Removing var
will not result in using .map
to mutate mutable elements of an array of reference type objects. Ie, you can just use your old approach (excluding, however, var
in the .map
closure signature).
class Gnome { var age = 42 } var gnomes = [Gnome(), Gnome(), Gnome()] gnomes = gnomes.map { $0.age = 150 return $0 } gnomes.forEach { print($0.age) }
However, if you just want to change the original array, rather than assign the result .map
to the new array, .forEach
might be a better choice than .map
.
gnomes.forEach { $0.age = 140 } gnomes.forEach { print($0.age) }
source share