修改数组最后一个元素的优雅方法是什么?

时间:2016-11-15 11:13:01

标签: ios swift

我有一组自定义类对象,我需要修改最后一个元素的属性。我知道"最后"和"第一"实现为getter,然而,这对我没有帮助:)除了通过索引访问最后一个元素之外还有其他方法吗?

更新

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

3 个答案:

答案 0 :(得分:4)

这是一个有效的最小例子。它表明您可以毫无问题地修改最后一个元素的属性。

class Dog {
    var age = 0
}

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

然而,听起来你正试图用dogs.last? = anotherDog替换最后一个元素而不是修改它。

<强>更新

有趣。我实际上不知道为什么协议会改变行为(我想我应该更多地研究协议),但这是一个干净的解决方案:

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
}

答案 1 :(得分:0)

请记住,您只能使用Sequences(例如Array)来做到这一点:

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

答案 2 :(得分:-1)

我会这样做

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

arr[arr.endIndex-1] = 5

它会给你

[1, 2, 3, 5]
不过,也许这个问题是重复的

编辑:

阵列安全访问 Safe (bounds-checked) array lookup in Swift, through optional bindings?

相关问题