Static Property in Swift

Level 4274 keystrokes

The static property total is shared by the whole class, while id belongs to each instance. Each init increments total and uses it as the new id, so it prints IDs: 1, 2, 3 and Total: 3.

Swift code

1class Counter {
// One value shared by the class, not by each instance
2 static var total = 0
// Each instance has its own id
3 var id: Int
4
5 init() {
// Inside init, the static property is accessed through the type name
6 Counter.total += 1
// The new total becomes this instance's id
7 self.id = Counter.total
8 }
9
// Type method; inside it, total needs no prefix (never called here)
10 static func reset() {
11 total = 0
12 }
13}
14
// Three instances get ids 1, 2 and 3
15let c1 = Counter()
16let c2 = Counter()
17let c3 = Counter()
// Prints IDs: 1, 2, 3
18print("IDs: \(c1.id), \(c2.id), \(c3.id)")
// Prints Total: 3
19print("Total: \(Counter.total)")

Output

IDs: 1, 2, 3
Total: 3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 11
  • )× 11
  • .× 7
  • =× 7
  • "× 4
  • \× 4
  • :× 3
  • {× 3
  • }× 3
  • ,× 2

More Swift examples at level 4

← Swift typing practice