简体   繁体   中英

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. I don't understand why the isMillionaire property remains false despite the if statement evaluating to true.

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.

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:

var isMillionaire: Bool {
  return balance > 1_000_000
}

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