我有一组自定义类对象,我需要修改最后一个元素的属性。我知道“last”和“first”是作为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
Run Code Online (Sandbox Code Playgroud)
我会这样做
var arr = [1,2,3,4]
arr[arr.endIndex-1] = 5
Run Code Online (Sandbox Code Playgroud)
它会给你
[1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,也许这个问题是重复的
编辑:
数组安全访问 Swift 中通过可选绑定进行安全(边界检查)数组查找?
安全(在空的情况下)和优雅:
foo.indices.last.map{ foo[$0].bar = newValue }
Run Code Online (Sandbox Code Playgroud)
请注意,您只对Sequences
s (如Array
)执行此操作,因为获取最后一个索引的集合可能需要迭代整个过程。
这是一个有效的最小示例。它表明您可以毫无问题地修改最后一个元素的属性。
class Dog {
var age = 0
}
let dogs = [Dog(), Dog()]
dogs.last?.age += 1 // Happy birthday!
Run Code Online (Sandbox Code Playgroud)
然而,听起来您正在尝试用类似的东西替换最后一个元素,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
}
Run Code Online (Sandbox Code Playgroud)