Can You Write Pure Functions in Swift?
You bet!
Before we start
If you are writing functions, you might be asked whether the code is a pure function or not. You’ll need to know, and you’ll need to be able to describe what it is. In steps this guide to help you out.
Before we start
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 13, and Swift 5.5.
Keywords and Terminology
Idempotent: An operation that produces the same results if executed multiple times
Pure Function: A function where the return value is only determined by its input values, without observable side effects
The theory
A pure function does not produce any side effects. This means:
- The function always returns the same value for the same inputs
- The function produces no side effects. That is, the function will not change the global state
Therefore a pure function should be run and the output is based wholly upon it’s inputs and doesn’t have the potential to mess up any other code.