arraysswiftmap-function

Map modify array of objects in Swift 2.2 (3.0)


I want to be able to modify my array of objects using map in Swift of the fly, without looping through each element.

Before here were able to do something like this (Described in more details here:

gnomes = gnomes.map { (var gnome: Gnome) -> Gnome in
    gnome.age = 140
    return gnome
}

Thanks for Erica Sadun and others, new proposals have gone through and we're now getting rid of C-style loops and using var inside the loop.

In my case I'm first getting a warning to remove the var in then an error my gnome is a constant (naturally)

My question is : How do we alter arrays inside a map or the new styled loops for that matter to be fully prepared for Swift 3.0?


Solution

  • If you want to keep that syntax, just use a (mutable) temporary variable

    gnomes = gnomes.map { (gnome: Gnome) -> Gnome in
      var mutableGnome = gnome
      mutableGnome.age = 140
      return mutableGnome
    }