在玩结构时,我发现了以下内容:
struct SomeStruct {
private(set) var uncount: Int
subscript(i: Int) -> Int {
uncount = i // <--'self' is immutable-----
return 3
}
}
let someStructInstance = SomeStruct(uncount: 3)
someStructInstance[345]
上面的代码无法编译,因为“self”是不可变的,并且您无法在下标中添加变异关键字。
然而,以下工作完美:
struct SomeStruct {
private(set) var uncount: Int
subscript(i: Int) -> Int {
get {
return 3
}
set {
uncount = i //<--works well now---
}
}
}
let someStructInstance = SomeStruct(uncount: 3)
someStructInstance[345]
问题:当下标函数都改变了struct属性时,为什么一个工作,而另一个工作呢?
答案 0 :(得分:5)
你的
subscript(i: Int) -> Int {
uncount = i // <--'self' is immutable-----
return 3
}
默认只定义一个下标 getter,,即非变异。
如果你真的需要改变getter中的属性那么
您可以将其声明为mutating get
:
subscript(i: Int) -> Int {
mutating get {
uncount = i
return 3
}
}
因此,getter不能与常量值一起使用 了,
let someStructInstance = SomeStruct(uncount: 3)
print(someStructInstance[345])
// error: Cannot use mutating getter on immutable value: 'someStructInstance' is a 'let'
它必须是一个变量:
var someStructInstance = SomeStruct(uncount: 3)
print(someStructInstance[345]) // 3
print(someStructInstance.uncount) // 345