“oldValue” and “newValue” default parameters names

2019-04-18 05:21发布

I am currently writing Swift 3 code in Xcode 8.

When using oldValue and newValue default parameters inside the willSet and didSet blocks, I am getting "unresolved identifier" compiler error.

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 Documentation for Swift 3 still seems to support these feature. I hope I am not missing anything here?

标签: ios swift swift3
4条回答
劫难
2楼-- · 2019-04-18 05:36

You didn't try to initialize the variable with a new object by which you can set your clojure:

var vc:UIViewController? = UIViewController(){
   willSet { 
       print("Old value is \(oldValue)")
   }
   didSet(viewController) {
       print("New value is \(newValue)")
   }
}
查看更多
走好不送
3楼-- · 2019-04-18 05:43
var vc:UIViewController? {
    willSet {
        print("New value is \(newValue)")
    }
    didSet {
        print("Old value is \(oldValue)")
    }
}
查看更多
beautiful°
4楼-- · 2019-04-18 05:53

You can also use vc:

var vc:UIViewController? {
    willSet {
        print("New value is \(newValue) and old is \(vc)")
    }
    didSet {
        print("Old value is \(oldValue) and new is \(vc)")
    }
}
查看更多
冷血范
5楼-- · 2019-04-18 05:54

The special variable newValue only works within willSet, while oldValue only works within 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.

查看更多
登录 后发表回答