Swift Functional Programming: Pure Functions

A pure function doesn’t reference any data outside of the function. If you supply a given input to a pure function, it always returns the same value. The following is a simple example of a pure function:

func increment(value: Int) -> Int {
return value + 1
}

The increment function is pure because it increments the value you supply to it. It doesn’t modify any outside variables. If you pass the value 9 to increment, it always returns 10.

The following code is a hypothetical example of an impure function that updates contact information based on the values of text fields in an app’s user interface:

The updateContactInfo function is impure because it modifies variables outside of the function: name, address, and phone.

Pure Functions Simplify Unit Testing

A big advantage of pure functions is they’re much easier to unit test. To test the increment function, all you have to do is create an integer, call increment, and assert the incremented value is correct.

I know increment is a simple function, but unit testing any pure function follows the same steps.

Create values for the arguments.

Call the function.

Assert the function returns the correct value.

Unit testing the updateContactInfo function would be painful. You would have to perform the following steps:

Create an instance of the data structure that contains the contact information.

2 thoughts on “Swift Functional Programming: Pure Functions”

Did you figure out how to approach pure functions that are composed of other pure functions? Unit testing each of them is simple, but testing the composite itself isn’t. (Unless you inject the parts as closures, which is kind of odd.)