ios - 当 newValue 没有分配任何内容时,为什么这段快速代码可以工作?

标签 ios swift oop computed-properties

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类(class)中使用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 的默认设置,相反,分配值的缺失让我感到困惑)

最佳答案

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

关于ios - 当 newValue 没有分配任何内容时,为什么这段快速代码可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31350035/

相关文章:

xcode - 如何在 Swift 中弯曲 UIViewController 的顶部?

sql - 面向对象的程序员如何了解数据库驱动的编程?

c# - 从抽象类对象列表访问子类的属性

iphone:UItableviewcell 滚动时重新加载

ios - 为什么我的UIView中的cocos2D场景没有响应?

xcode - 从一个文本字段输入文本到多个标签(在 swift 中)

objective-c - 当 Swift 桥接头导入导入 Hopscotch-Swift.h 本身的文件时,如何防止循环引用

iOS 使用 XEP-0191 阻止用户

ios - UINavigationBar 的奇怪行为

python - 我如何使用 __.init__ 并为 python 进行 OOP