ios willSet / didSet 中的“oldValue”和“newValue”默认参数名称无法识别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39559212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"oldValue" and "newValue" default parameters names inside willSet / didSet unrecognized
提问by Adithya
I am currently writing Swift 3 code in Xcode 8.
我目前正在 Xcode 8 中编写 Swift 3 代码。
When using oldValue
and newValue
default parameters inside the willSet
and didSet
blocks, I am getting "unresolved identifier"
compiler error.
在and块中使用oldValue
和newValue
默认参数时,出现编译器错误。willSet
didSet
"unresolved identifier"
I have a very basic code as below
我有一个非常基本的代码如下
var vc:UIViewController? {
willSet {
print("Old value is \(oldValue)")
}
didSet(viewController) {
print("New value is \(newValue)")
}
}
Apple Documentationfor Swift 3 still seems to support these feature. I hope I am not missing anything here?
Swift 3 的Apple 文档似乎仍然支持这些功能。我希望我在这里没有遗漏任何东西?
回答by FranMowinckel
You can also use vc
:
您还可以使用vc
:
var vc:UIViewController? {
willSet {
print("New value is \(newValue) and old is \(vc)")
}
didSet {
print("Old value is \(oldValue) and new is \(vc)")
}
}
回答by Robin Stewart
The special variable newValue
only works within willSet
, while oldValue
only works within didSet
.
特殊变量newValue
仅在 内有效willSet
,而oldValue
仅在 内有效didSet
。
The property as referenced by its name (in this example vc
) is still bound to the old value within willSet
and is bound to the new value within didSet
.
由其名称(在此示例中vc
)引用的属性仍绑定到 中的旧值,willSet
并绑定到 中的新值didSet
。
回答by Dmytro Shvetsov
var vc:UIViewController? {
willSet {
print("New value is \(newValue)")
}
didSet {
print("Old value is \(oldValue)")
}
}
回答by Wissa
It's important to know that the special variable newValue
only works within willSet
, while oldValue
only works within didSet
.
重要的是要知道特殊变量newValue
仅适用于willSet
,而oldValue
仅适用于didSet
。
var vc: UIViewController? {
willSet {
// Here you can use vc as the old value since it's not changed yet
print("New value is \(newValue)")
}
didSet {
// Here you can use vc as the new value since it's already DID set
print("Old value is \(oldValue)")
}
}
回答by gomozor
You didn't try to initialize the variable with a new object by which you can set your clojure:
您没有尝试使用可以设置 clojure 的新对象来初始化变量:
var vc:UIViewController? = UIViewController(){
willSet {
print("Old value is \(oldValue)")
}
didSet(viewController) {
print("New value is \(newValue)")
}
}
回答by HymanMao
That's why we use NSKeyValueObservation to monitor class object
这就是为什么我们使用 NSKeyValueObservation 来监控类对象