Centurion Centurion - 17 days ago 5
Swift Question

What is an elegant way of modifying last element of an array?

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

jjs jjs
Answer

Here's a minimal example that works. It shows that you can modify the last element's properties without issues.

class Dog {
    var age = 0
}

let dogs = [Dog(), Dog()]
dogs.last?.age += 1 // Happy birthday!

However, it sounds like you are trying to replace the last element with something like dogs.last? = anotherDog instead of modifying it.

Update:

Interesting. I don't actually know why the protocol changes the behavior (I guess I should study protocols more), but here's a clean solution:

protocol DogProtocol {
    var age: Int { get set }
}

class Dog: DogProtocol {
    var age = 0
}

var dogs: [DogProtocol] = [Dog(), Dog()]

if var birthdayBoy = dogs.last {
    birthdayBoy.age += 1
}
Comments