ios - 属性(property)观察员及其行为

标签 ios swift properties swift3

我有一个示例类和一个 Int 类型的属性,如下所示:

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("about to set steps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue {
                print("Added \(totalSteps - oldValue) steps")
            }

        }
    }
}

现在,当我创建此类的实例并为我的 var totalSteps 分配一个数字时,如下所示:

let anObj = StepCounter()

anObj.totalSteps = 2000

我得到了预期的控制台输出:

about to set steps to 2000
Added 2000 seteps

但是当我执行 anObj.totalSteps -= 1 时,我只得到 willSet 输出说 about to set steps to 1999didSet 永远不会被执行。发生了什么以及为什么我没有执行 willSet 打印语句?帮帮忙,谢谢。

最佳答案

在你的didSet中你有:

if totalSteps > oldValue

但是当您执行 anObj.totalSteps -= 1 时,总步数不会大于旧值!

所以 print 没有像预期的那样执行。 :)

关于ios - 属性(property)观察员及其行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587903/

相关文章:

swift - EnumerateChildNodesWithName,似乎无法删除节点

iphone - retain setter 是如何用@synthesize 实现的?

properties - 是否可以从ant设置maven属性?

ios - iCloud 同步失败并显示 "CoreData: Ubiquity: Invalid option: the value for NSPersistentStoreUbiquitousContentNameKey should not contain periods"

ios - 带有层角半径和阴影的 UILabel

ios - 自定义返回 UIBarButton 与原始标题相同?

ios - 我在 appDelegate 中收到错误?

ios - UICollectionViewCell 中的自动布局错误

ios - Swift MultipeerConnectivity 崩溃 DateComponents unconditionallyBridgeFromObjectiveC

java - 从单个文本文件加载大量属性文件并插入 LinkedHashMap