简体   繁体   中英

Questions regarding to value setting and getters and setters in Swift

Hi I just picked up Swift and am following the Stanford open course. I was making this calculator and got a breakpoint at the line of userIsInTheMiddleOfTyping = false in the func enter part when I placed the line before operandStack.append(displayValue) . After I placed the line at the bottom of the function, the problem was solved. But why?

Also, I don't get the part of get and set in displayValue part. Can anyone help to explain how this part is executed. And where is the newValue from? why does it represent whatever value on the display? The code is followed. I would appreciate any answers and comments!

class ViewController: UIViewController {

    @IBOutlet weak var display: UILabel!

    var userIsInTheMiddleOfTypingAnNumber = false

    @IBAction func AppendDigit(sender: UIButton) {
        let digit = sender.currentTitle!
        if userIsInTheMiddleOfTypingAnNumber {
            display.text = display.text! + digit
        }
        else{
            display.text = digit
            userIsInTheMiddleOfTypingAnNumber = true
        }
    }
    var operandStack = Array<Double>()
    @IBAction func enter() {
        operandStack.append(displayValue)
        println("operandStack=\(operandStack)")
        userIsInTheMiddleOfTypingAnNumber = false
    }

    var displayValue: Double{
        get{
            return NSNumberFormatter().numberFromString(display.text!)!.doubleValue

        }
        set{
            display.text = "\(newValue)"
            userIsInTheMiddleOfTypingAnNumber = false

        }

    }
}

get and set are the keywords used in Swift to define custom getters and setters to a property.

newValue is the default name for the new value that will be assigned to the variable at the end of the setter, it allows you to check various things before assigning it.

For the first part of your question I don't quite understand what's not working for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM