"oldValue"和"newValue"默认参数名称里面的willSet/didSet无法识别

Adi*_*hya 24 ios swift swift3

我目前正在Xcode 8中编写Swift 3代码.

当在和块中使用oldValuenewValue默认参数时,我收到编译器错误.willSetdidSet"unresolved identifier"

我有一个非常基本的代码如下

var vc:UIViewController? {
    willSet {
        print("Old value is \(oldValue)")
    }
    didSet(viewController) {
        print("New value is \(newValue)")
    }
}
Run Code Online (Sandbox Code Playgroud)

Swift 3的Apple文档似乎仍然支持这些功能.我希望我在这里不遗漏任何东西?

Fra*_*kel 50

您还可以使用vc:

var vc:UIViewController? {
    willSet {
        print("New value is \(newValue) and old is \(vc)")
    }
    didSet {
        print("Old value is \(oldValue) and new is \(vc)")
    }
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*art 26

特殊变量newValue只能在其中工作willSet,而oldValue只能在其中工作didSet.

其名称引用的属性(在此示例中vc)仍然绑定到其中的旧值,willSet并绑定到其中的新值didSet.


Dmy*_*sov 13

var vc:UIViewController? {
    willSet {
        print("New value is \(newValue)")
    }
    didSet {
        print("Old value is \(oldValue)")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 从你的答案中,我能够推断出`newValue`在`willSet`中工作,而'oldValue`适用于`didSet`块,因为没有自定义参数. (2认同)

Wis*_*ssa 10

重要的是要知道特殊变量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)") 
    }
}
Run Code Online (Sandbox Code Playgroud)