I have an array of custom class objects and I need to modify a property of the last element. I know "last" and "first" are implemented as getters, however, that doesn't help me :) Is there another way than accessing the last element by index?
UPDATE
protocol DogProtocol {
var age: Int {get set}
}
class Dog: DogProtocol {
var age = 0
}
var dogs = Array<DogProtocol>()
dogs.append(Dog())
dogs.last?.age += 1 // Generates error in playground: left side of mutating operator isn't mutable: 'last" is a get-only property
Safe (in case of empty) and elegant:
foo.indices.last.map{ foo[$0].bar = newValue }
Mind you only do this with Sequences
s (like Array
) as with collections getting the last index may require iterating the whole thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With