๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Type Properties

A type property is a property that belongs to the type itself rather than to one instance. It is declared with the static keyword inside the type.

Counting instances through the type

Each Player creation raises the shared createdCount by one. The count is read through the Player name after three creations.

class Player {
    static var createdCount = 0
    init() {
        Player.createdCount += 1
    }
}
_ = Player()
_ = Player()
_ = Player()
print(Player.createdCount)

A static computed property

The Converter type stores one rate and computes a larger one from it. Changing the stored rate changes the computed answer on the next read.

struct Converter {
    static var centsPerDollar = 100
    static var centsPerTenDollars: Int {
        get {
            return centsPerDollar * 10
        }
    }
}
print(Converter.centsPerDollar)
print(Converter.centsPerTenDollars)
Converter.centsPerDollar = 50
print(Converter.centsPerTenDollars)

A type level constant

No GameRules value is made in this program. Both constants are read straight through the type name.

struct GameRules {
    static let maxPlayers = 4
    static let boardSize = 64
}
print(GameRules.maxPlayers)
print(GameRules.boardSize)

Example

class Account {
    static var openedCount = 0
    static let bankName = "North Bank"
    init() {
        Account.openedCount += 1
    }
}
_ = Account()
_ = Account()
print(Account.bankName)
print(Account.openedCount)

Key points

  • A type property is read through the type name rather than through an instance.
  • A static stored property holds one value shared by the whole type.
  • Every instance of the type sees that same shared value.
  • A static computed property works out its value on each read through the type name.
  • A static constant holds a fixed value that can be read with no instance at all.

In this example, the Account class holds a shared openedCount and a fixed bankName as type properties. Making two accounts raises the shared count to 2. The first print reads the constant through the type name and shows North Bank, and the last print shows the shared count 2.

Note

Making an instance is never required to read a type property.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How is a type property read?