Search code examples
iosswiftoopcomputed-properties

Why does this swift code work when newValue has nothing assigned to it?


import UIKit

class ViewController: UIViewController {

@IBOutlet weak var display: UILabel!

var inMid = false

@IBAction func appendDigit(sender: UIButton) {
    let digit = sender.currentTitle!
    if inMid{
        display.text = display.text! + digit
    }else{
        display.text = digit
        inMid = true
    }
}


var operandStack = Array<Double>()
@IBAction func enter() {
    inMid = false
    operandStack.append(displayValue)
    println("operandStack = \(operandStack)")
}


var displayValue:Double{
    get {
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display.text = "\(newValue)"
    }
}

}

This is the part of code used in the latest Standford IOS 8 course using swift to build a calculator(Youtube address: https://www.youtube.com/watch?v=QLJtT7eSykg)

Every time I call enter() (press enter), a new number is supposed to be saved in a stack. For example: "8, enter()" --> {8}, "16, enter()" --> {8,16}.

I got confused about the computed property "displayValue" here. There is nothing assigned to the "newValue". If there is something like "displayValue = 8", then I know "newValue" is 8, and it all makes sense. But there is not such thing.

How come it still works?

(What I mean is not the name "newValue" itself,I know it is a default setting by Swift, instead, the missing of assigned value is the one that confuses me)


Solution

  • "newValue" is an implicitly defined variable in swift. What he does is a very neat way of letting the label show the values of the double "displayValue" Every time displayValue is changed, the label is automatically updated with the newest (double) value. Or when you write: displayValue = 45.0, the label will also show this value. Very handy when you constantly need to update textfield or labels with data you get from databases, rest interfaces, etc. What "newValue" does is taking the last "setter" value holding that.