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

Safe (in case of empty) and elegant:

foo.indices.last.map{ foo[$0].bar = newValue }

Mind you only do this with Sequencess (like Array) as with collections getting the last index may require iterating the whole thing.


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
}

I would do it this way

var arr = [1,2,3,4]

arr[arr.endIndex-1] = 5

it would give you

[1, 2, 3, 5]

Btw, maybe this question is a duplicate

EDIT:

array safe access Safe (bounds-checked) array lookup in Swift, through optional bindings?

Tags:

Ios

Swift