Adithya
Adithya

Reputation: 4705

"oldValue" and "newValue" default parameters names inside willSet / didSet unrecognized

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?

Upvotes: 57

Views: 65859

Answers (6)

JackMao
JackMao

Reputation: 1

That's why we use NSKeyValueObservation to monitor class object

Upvotes: -8

Wissa
Wissa

Reputation: 1592

It's important to know that the special variable newValue only works within willSet, while oldValue only works within 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)") 
    }
}

Upvotes: 17

Robin Stewart
Robin Stewart

Reputation: 3883

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.

Upvotes: 75

FranMowinckel
FranMowinckel

Reputation: 4343

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)")
    }
}

Upvotes: 96

gomozor
gomozor

Reputation: 107

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)")
   }
}

Upvotes: 0

Dmytro Shvetsov
Dmytro Shvetsov

Reputation: 1006

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

Upvotes: 25

Related Questions