Mutating Method in Swift
Level 3199 keystrokes
Methods of a struct cannot change its properties unless they are marked mutating. The counter is incremented by 1 and then by 5, so it prints 6.
Swift code
1struct Counter { // Stored property with default value 02 var count = 03 // mutating lets the method modify self's properties4 mutating func increment() { // Adds 1 to count5 count += 16 }7 // _ means the argument has no label: counter.add(5)8 mutating func add(_ n: Int) { // Adds n to count9 count += n10 }11}12 // Must be var: mutating methods cannot be called on a let constant13var counter = Counter()// count becomes 1, then 614counter.increment()15counter.add(5)// Prints 616print(counter.count)Output
6
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.
(× 6)× 6=× 4.× 3{× 3}× 3+× 2_× 1:× 1