Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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
like image 454
Centurion Avatar asked Nov 15 '16 11:11

Centurion


1 Answers

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.

like image 89
mxcl Avatar answered Oct 13 '22 22:10

mxcl