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 0
2 var count = 0
// Struct methods that change properties must be marked mutating
3 mutating func increment() {
// Add 1 to count
4 count += 1
5 }
// A normal method only reads properties, so no mutating is needed
6 func display() {
7 print("Count: \(count)")
8 }
9}
10
// Must be var: mutating methods cannot be called on a let constant
11var c = Counter()
// Called twice, so count goes 0 → 1 → 2
12c.increment()
13c.increment()
// Prints Count: 2
14c.display()

Output

Count: 2
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.

  • (× 8
  • )× 8
  • .× 3
  • {× 3
  • }× 3
  • =× 3
  • "× 2
  • :× 1
  • \× 1
  • +× 1

More Swift examples at level 3

← Swift typing practice