Property observers
For your Level implementation, it would be useful to automatically set the highestLevel when the player unlocks a new one. For that, you’ll need a way to listen to property changes. Thankfully, there are a couple of property observers that get called before and after property changes. You can use willSet and didSet similar to the way you used set and get:
struct Level {
static var highestLevel = 1 let id: Int
var boss: String var unlocked: Bool {
didSet {
if unlocked && id > Level.highestLevel { Level.highestLevel = id
}
}
}
}
Now, when the player unlocks a new level, it will update the highestLevel type property if the level is a new high. There are a couple of things to note here:
- You can access the value of unlocked from inside the didSet observer. Remember that didSet gets called after the value has been set.
- Even though you’re inside an instance of the type, you still have to access the type properties with their full names like Level.highestLevel rather than just highestLevel alone.
Also, keep in mind that the willSet and didSet observers are not called when a property is set during initialization; they only get called when you assign a new value to a fully-initialized instance. That means property observers are only useful for variable properties, since constant properties are only set during initialization.