Method Definition in Swift
Level 3176 keystrokes
Defines methods in a struct: increment is marked mutating because it changes a property, and display only reads it. After two increments it prints "Count: 2".
Swift code
1struct Counter { // A stored property with a default value of 02 var count = 0 // Struct methods that change properties must be marked mutating3 mutating func increment() { // Add 1 to count4 count += 15 } // A normal method only reads properties, so no mutating is needed6 func display() {7 print("Count: \(count)")8 }9}10 // Must be var: mutating methods cannot be called on a let constant11var c = Counter()// Called twice, so count goes 0 → 1 → 212c.increment()13c.increment()// Prints Count: 214c.display()Output
Count: 2
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.
(× 8)× 8.× 3{× 3}× 3=× 3"× 2:× 1\× 1+× 1