0

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
mfaani
  • 33,269
  • 19
  • 164
  • 293
Yuni
  • 25
  • 7
  • Welcome to Stack Overflow. Can you please edit your question and remove the image and paste actual code? – mfaani Jun 27 '20 at 11:56

1 Answers1

4

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
}
EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50