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 instance2 static var total = 0 // Each instance has its own id3 var id: Int4 5 init() { // Inside init, the static property is accessed through the type name6 Counter.total += 1 // The new total becomes this instance's id7 self.id = Counter.total8 }9 // Type method; inside it, total needs no prefix (never called here)10 static func reset() {11 total = 012 }13}14 // Three instances get ids 1, 2 and 315let c1 = Counter()16let c2 = Counter()17let c3 = Counter()// Prints IDs: 1, 2, 318print("IDs: \(c1.id), \(c2.id), \(c3.id)")// Prints Total: 319print("Total: \(Counter.total)")Output
IDs: 1, 2, 3 Total: 3
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