简体   繁体   English

在 willSet 观察者中计算后未更新结构中的属性

[英]A property in a struct not being updated after being computed in willSet observer

Sorry in advance if my question comes across being stupid, I'm currently learning property observers and I've been given an example from a great swift tutorial online to determine if the code is valid, I correctly assumed it was and decided to implement it in Swift playgrounds.提前抱歉,如果我的问题很愚蠢,我目前正在学习财产观察员,我已经从一个很棒的 swift 在线教程中获得了一个示例,以确定代码是否有效,我正确地假设它是并决定实施它在 Swift 操场上。 I don't understand why the isMillionaire property remains false despite the if statement evaluating to true.我不明白为什么尽管 if 语句评估为 true,但isMillionaire属性仍然为 false。

struct BankAccount{
var name: String
var isMillionaire = false
var balance: Int {
    didSet {
        if balance > 1_000_000 {
            isMillionaire = true
        } else {
            isMillionaire = false
        }
    }
  }
}

var bankUser1 = BankAccount(name: "John Appleseed", balance: 2_000_000)
print(bankUser1.isMillionaire) //Returns false

Property observers are not called on initialisation, only when the value is set after that, that's why didSet is not being executed.初始化时不会调用属性观察器,只有在此之后设置值时,这就是不执行didSet的原因。

In this specific case, since isMillionaire is completely derived from balance and shouldn't be able to be updated directly, I would recommend using a computed property, so it would look like this:在这种特定情况下,由于isMillionaire完全来自balance并且不能直接更新,我建议使用计算属性,因此它看起来像这样:

var isMillionaire: Bool {
  return balance > 1_000_000
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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