Hello. Often I need update each element in collections. And I wrote next function
public protocol Adjust {
mutating func preAnimationAdjust()
}
func adjustEachElementInCollection<C: MutableCollection>(c: inout C) where C.Element: Adjust {
for index in c.indices {
var item = c[index]
item.preAnimationAdjust()
c[index] = item
}
}
And next test gives away a correct result
struct Bee: PreAnimationAdjust {
var name: String
mutating func preAnimationAdjust() {
name += "A"
}
}
public func test() {
var bees = [Bee(name: "Anna"), Bee(name: "Anton"), Bee(name: "Kit")]
print(bees) // [Bee(name: "Anna"), Bee(name: "Anton"), Bee(name: "Kit")]
adjustEachElementInCollection(c: &bees)
print(bees) //[Bee(name: "AnnaA"), Bee(name: "AntonA"), Bee(name: "KitA")]
}
Is it safe approach to mutation a collection? In final I need same type of a collection after mutation, therefore the .map does not fit.