a 如何在结构中使用 setter 的值进行操作?
How can a operate with value of setter in structs?
我有 swift 结构的 getter 和 setter 代码。
newValue
的值是如何进入这个 setter 的?不知道是怎么定义的
struct Program {
var allResults : [String] = []
var items: Int {
get {
return allResults.count
}
set {
let result = String(newValue * 100) // what's that newValue, how did it get there?
allResults.append(result)
}
}
叫做ShorthandSetter宣言.
引用自 Swift 3 本书:
If a computed property’s setter does not define a name for the new
value to be set, a default name of newValue is used.
如果你想要更好的可读格式,你可以使用这个:
...
set (newItems) { //add your own variable named as you like
let result = String(newItems * 100)
allResults.append(result)
}
...
我有 swift 结构的 getter 和 setter 代码。
newValue
的值是如何进入这个 setter 的?不知道是怎么定义的
struct Program {
var allResults : [String] = []
var items: Int {
get {
return allResults.count
}
set {
let result = String(newValue * 100) // what's that newValue, how did it get there?
allResults.append(result)
}
}
叫做ShorthandSetter宣言.
引用自 Swift 3 本书:
If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used.
如果你想要更好的可读格式,你可以使用这个:
...
set (newItems) { //add your own variable named as you like
let result = String(newItems * 100)
allResults.append(result)
}
...