Postfix and Prefix in Swift

Precedence is also important!

Postfix and prefix operators are possible in Swift. Perhaps it is something you might think about doing?

Image for post
Image for post
Photo by Clark Young on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Be familiar with Functions (guide HERE)
  • Some familiarity with Swift’s inout keyword (guide HERE)
  • Have some understanding of postfix and prefix (guide HERE)

Terminology

Function: a group of statements that together can perform a function

Operator: A symbol like minus that shows an operation

Postfix: A mathematical notation in which operators follow operands

Prefix: A mathematical notation in which operands follow operators

Reverse Polish Notation (RPN): A mathematical notation in which operators follow operands

What is Postfix and Prefix

Swift allows you to present your own postfix and prefix custom operators.

Postfix

Let us take an example. Thinking about postfix perhaps the most simple example is Reverse Polish Notation , and we can

postfix func ++( x: inout Int) -> Int {
let current = x
x += 1
return current
}

Which can be called (perhaps unsurprisingly with the following):

var num = 1
num++

Prefix

Prefix is similar to postfix, but when used the operator is placed in front of the variable

prefix func ++( x: inout Int) -> Int {
let current = x
x += 1
return current
}

so we call this with

var num = 1
--num

Precedence in Swift for prefix and postfix operators

There is no reason to specify precedence for prefix and postfix operators, as by definition they have the same precedence listed — the postfix operator is always applied first.

Conclusion:

Creating custom operators is actually quite simple in Swift. The advantage in doing so is that we can write more succinct and better quality code.

Fantastic.

Extend your knowledge

  • You can (if you choose) read Apple’s documents HERE
  • If you want to understand more about Reverse Polish Notation you can read HERE

The Twitter contact:

Any questions? You can get in touch with me here

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store