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

}

这是最新的Standford IOS 8课程中使用swift构建计算器的部分代码(Youtube地址:https ://www.youtube.com/watch?v=QLJtT7eSykg )

每次我调用 enter()(按 enter)时,都应该将一个新数字保存在堆栈中。例如:"8, enter()" --> {8}, "16, enter()" --> {8,16}。

我对这里的计算属性“displayValue”感到困惑。没有分配给“newValue”的任何内容。如果有类似“displayValue = 8”的东西,那么我知道“newValue”是 8,这一切都说得通。但是没有这样的事情。

怎么还能用?

(我的意思不是名称“newValue”本身,我知道它是 Swift 的默认设置,相反,分配值的缺失让我感到困惑)

4

1 回答 1

0

"newValue" 是 swift 中隐式定义的变量。他所做的是一种非常巧妙的方法,让标签显示双“displayValue”的值每次更改 displayValue 时,标签都会自动更新最新(双)值。或者当你写:displayValue = 45.0,标签也会显示这个值。当您经常需要使用从数据库、rest 接口等获取的数据更新文本字段或标签时非常方便。“newValue”所做的是获取最后一个“setter”值。

于 2015-07-11T20:46:06.313 回答