Map modifies an array of objects in Swift 2.2 (3.0)

I want to be able to change my array of objects using map in Swift to fly without iterating over each element.

Before that, something could be done here (described in more detail here :

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

Thanks for Erica Sadun and others, the new proposals have passed, and now we get rid of C-style loops and use var inside the loop.

In my case, I get a warning first to remove var , and then my gnome error is constant (naturally)

My question is: how can we change arrays inside a map or new stylized loops to be fully prepared for Swift 3.0?

+5
source share
3 answers

If you want to keep this syntax just use a temporary variable (mutable)

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

(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 } /* result */ gnomes.forEach { print($0.age) } // 3x 150 

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 } /* result */ gnomes.forEach { print($0.age) } // 3x 140 
+14
source

Given:

 struct Gnome { var age: Int = 0 } var gnomes = Array(count: 5, repeatedValue: Gnome()) 

... there are two worthy options. The first is like @vadian:

 gnomes = gnomes.map{ var gnome = $0 gnome.age = 70 return gnome } 

While the second retains control over the "aging" of private and simplifies the display at the point of call:

 struct Gnome { private(set) var age: Int = 0 func aged(age: Int) -> Gnome { var gnome = self gnome.age = age // any other ageing related changes return gnome } } gnomes = gnomes.map{ $0.aged(140) } 

Of course, reference types still have a place in programming, which may well be better in this case. The three that we experience here indicate that we are trying to view these structures as if they were objects. If this is what you need, then you should consider implementing Gnome as a class .

+1
source

Source: https://habr.com/ru/post/1245901/


All Articles