Type properties
In the previous section, you learned how to associate stored and computed properties with instances of a particular type. The properties on your instance of TV are separate from the properties on my instance of TV.
However, the type itself may also need properties that are common across all instances. These properties are called type properties.
Imagine you’re building a game with many levels. Each level has a few attributes, or stored properties:
struct Level { let id: Int
var boss: String var unlocked: Bool
}
let level1 = Level(id: 1, boss: "Chameleon", unlocked: true) let level2 = Level(id: 2, boss: "Squid", unlocked: false)
let level3 = Level(id: 3, boss: "Chupacabra", unlocked: false) let level4 = Level(id: 4, boss: "Yeti", unlocked: false)
You declare a type property using static for value-based types like structures. You can use a type property to store the game’s progress as the player unlocks each level:
struct Level {
static var highestLevel = 1 let id: Int
var boss: String var unlocked: Bool
}
Here, highestLevel is a property on Level itself rather than on the instances. That means you don’t access a type property on an instance:
// Error: you can't access a type property on an instance let highestLevel = level3.highestLevel
Instead, you access it on the type itself:
let highestLevel = Level.highestLevel // 1
This means you can retrieve the same stored property value from anywhere in the code for your app or algorithm. The game’s progress is accessible from any level or
any other place in the game, like the main menu.