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 0
2 var count = 0
3
// mutating lets the method modify self's properties
4 mutating func increment() {
// Adds 1 to count
5 count += 1
6 }
7
// _ means the argument has no label: counter.add(5)
8 mutating func add(_ n: Int) {
// Adds n to count
9 count += n
10 }
11}
12
// Must be var: mutating methods cannot be called on a let constant
13var counter = Counter()
// count becomes 1, then 6
14counter.increment()
15counter.add(5)
// Prints 6
16print(counter.count)

Output

6
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.

  • (× 6
  • )× 6
  • =× 4
  • .× 3
  • {× 3
  • }× 3
  • +× 2
  • _× 1
  • :× 1

More Swift examples at level 3

← Swift typing practice