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
}