Reputation: 1094
In the Apple documentation for type properties the following code is given:
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
// cap the new audio level to the threshold level
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
// store this as the new overall maximum input level
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
The type properties are defined in a similar way to the "static" variables of the C language. In the example above, what would be the advantage of declaring type properties, and if they aren't declared what would be the effect or what difference would it make?
Upvotes: 3
Views: 1039
Reputation: 4254
Type variables, as the name implies, are variables for the whole type, as opposed to instance variables, which are variables for each of the instances.
That means, in the case of the code you posted, that every AudioChannel
you create will have the same values for thresholdLevel
and maxInputLevelForAllChannels
. And when something changes those variables all instances will have access to the new values.
Upvotes: 3