Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Overload the Prefix & Postfix Operators for Custom Swift Types
Written by Team Kodeco

In Swift, operators can be defined as prefix or postfix, which changes the order in which the operation is performed. Prefix operators are applied before the operand, while postfix operators are applied after the operand.

Here’s an example of how you might define the prefix and postfix operators for a custom IntCounter class:

struct IntCounter {
  var count: Int
  init(count: Int) {
    self.count = count
  }
}

extension IntCounter {
  static prefix func ++ (counter: inout IntCounter) -> IntCounter {
    counter.count += 1
    return counter
  }
  static postfix func ++ (counter: inout IntCounter) -> IntCounter {
    let retval = counter
    counter.count += 1
    return retval
  }
}

var counter = IntCounter(count: 0)
let a = ++counter
print(a.count)        // 1
print(counter.count)  // 1
let b = counter++
print(b.count)       // 1
print(counter.count) // 2

In this code, the ++ operator is defined as both a prefix and a postfix operator for the IntCounter struct. The difference between the two is in the order of operations.

  • In the prefix operator, the value of the counter is incremented first, then the new value of counter is returned.
  • In the postfix operator, the value of the counter is returned first, and then incremented.

This means that when the prefix operator is used, the value of counter and the returned value will both be incremented. However, when the postfix operator is used, the returned value will be the original value of counter before it was incremented.

That’s why the first two print statements have the same value and the last two have different values.

© 2024 Kodeco Inc.