Skip to content

Instantly share code, notes, and snippets.

@hanawat
Created January 21, 2016 23:05
Show Gist options
  • Save hanawat/e59df5b50edf6eaa7ce2 to your computer and use it in GitHub Desktop.
Save hanawat/e59df5b50edf6eaa7ce2 to your computer and use it in GitHub Desktop.
Notice can be understood as the change property before or after.
struct Product {
let cost: Int
var profit = 0
var count = 0
init(cost: Int, price: Int) {
self.cost = cost
self.price = price
}
var price: Int {
willSet {
count += 1
profit = newValue - cost
} didSet {
print("\(oldValue) => \(price)")
}
}
}
var 🍊 = Product(cost: 100, price: 200)
🍊.price = 400
🍊.price = 300
🍊.price = 500
// 3 times change price. Profit is 400.
print("\(🍊.count) times change price. Profit is \(🍊.profit).")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment