Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 146 ยท Advanced Swift

Functional Techniques

Practical functional programming in Swift: pure functions, immutability, composition, currying, map and flatMap on Optional, Array and Result, memoization and pitfalls.

Swift is not a purely functional language, and it does not try to be. It is a multi-paradigm language that happens to have first-class functions, closures, generics, value types and a standard library full of map, filter and reduce. That combination makes a functional style natural: small functions that take values and return values, data that does not change underneath you, and programs assembled by plugging functions together.

You have already used many of these ideas without naming them. This lesson names them, shows how they fit together, and gives you a toolbox of techniques that make code easier to test and reason about: pure functions, immutability, composition, currying and partial application, and the "map and flatMap" pattern that people call monads. We will translate every term into plain Swift, and we will be honest about where the functional style pays off and where ordinary imperative Swift is better.

You do not need category theory to use these techniques. If a word such as monad sounds scary, ignore the word and look at the code: it is just a type with map and flatMap that chains steps that might fail, produce many results or carry extra information.

Pure functions

A function is pure when two things hold. First, its result depends only on its arguments, so the same input always gives the same output. Second, it has no side effects: it does not modify anything outside itself, print, read the clock or touch files. max(3, 8) is pure. A function that appends to a global array or reads Date() is not.

Pure functions are easy to test (no setup, no mocks), easy to reason about (you can replace a call with its result), safe to run on any thread, and easy to cache. Compare two versions of the same job:

Swift Pure and impure functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The impure call returns 5 and then 10, although the arguments were identical, while the pure call returns 5 5. discounted prints 60.0, and mapping it over three prices prints [90.0, 36.0, 7.2]. The pure version moved the state out of the function: the caller keeps the total and passes it in. This is the central trick of functional design. You do not remove state; you make it explicit and push it to the edges of the program, where reading input, printing and storing happen.

A practical rule: write your core logic as pure functions over value types, and keep a thin imperative shell around it that talks to the outside world. Tests then cover the core without any mocking.

Immutability with value types

Swift gives you immutability almost for free. let makes a binding constant, and structs are value types, so passing one to a function hands over a copy. A function cannot change the caller's struct by accident, and two parts of a program never share a mutable object unless you choose classes. Functional code uses structs with let properties, or copies and changes only the part that differs:

Swift Immutable values and copying with changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first two lines show that ada is unchanged (Profile(name: "Ada", age: 36, tags: ["math"])) while older has age 37 and the extra tag. The point example prints Point(x: 0, y: 0) Point(x: 3, y: 4), and sorted() leaves the original alone: [1, 2, 3] [3, 1, 2]. This costs less than it sounds. Arrays and strings use copy-on-write (see Value vs reference types), so a copy is only made when one of the copies changes. The standard library also follows a naming rule that signals purity: sorted() and reversed() return new values, while sort() and reverse() mutate in place. Name your own functions the same way.

Mutation is not forbidden, only contained. A function that builds a result with a local var is still pure from the outside, as long as the variable never escapes. Swift is happy with that, and it is often faster than a purely recursive version.

Functions as values

Functions in Swift are values with a type such as (Int) -> Int. You can store them, pass them to other functions, return them and put them in arrays (Function Types and Closures cover the basics). Functions that take or return functions are higher-order functions, and they are the building blocks for everything below.

Swift Functions in arrays and returned from functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see 14 21, then [20, 30, 11], then 20 and hey!!. makeMultiplier returns a closure that remembers factor; two calls give two independent functions. applyTwice works with any type T, because the function and the value have to agree on it.

Composition

If f turns an A into a B and g turns a B into a C, you can build a function that turns an A into a C by running them in order. That is composition. It lets you build big behavior from small, individually testable pieces. Swift has no built-in operator for it, but you can declare one:

Swift Composing functions with a custom operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

import Foundation is needed for trimmingCharacters. The call clean(" hello swift ") prints HELLO SWIFT!, the second line prints false true, and combined(4) runs 4 + 1, then * 10, then - 3 and prints 47.

Notice how the types guard you: length >>> isLong compiles because the output of the first step (Int) is the input of the second. Try isLong >>> length and the compiler refuses, because a Bool is not a String.

The standard library also has composition-like idioms that need no custom operators. Methods chain naturally (names.map(...).filter(...).sorted()), and method references are values: String.uppercased has the type (String) -> () -> String. That first step takes the string and gives back the method, so ["a", "b"].map(String.uppercased) compiles but returns an array of functions (it prints [(Function), (Function)]), while map { $0.uppercased() } gives the strings you wanted. Prefer plain chaining for everyday code, and reach for an operator such as >>> only when a long composition is used many times and the team agrees on the symbol.

Custom operators are the first thing a new teammate cannot search for. Keep them few, give them a documented precedence group, and prefer a named function (compose(f, g) or f.then(g)) in code that is shared widely.

Currying and partial application

A function of two arguments, (A, B) -> C, can be turned into a function that takes A and returns a function from B to C: (A) -> (B) -> C. That transformation is currying. Using it, you fix some arguments now and supply the rest later, which is called partial application. Swift does not curry automatically, but you can write the conversion once, generically:

Swift Currying and partial application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

powersOfTwo(10) prints 1024 and curriedPower(3)(4) prints 81; the same line shows 1024 81. The next lines print x-y, then [12.0, 24.0, 60.0] for the prices with 20 percent tax added, then [5, 2] and ["a", "bb"].

In everyday Swift you rarely write curry yourself. Closures capture values, so makeMultiplier(2) from earlier is already partial application. Swift also gives every instance method a curried form when you refer to it through its type: Type.method has the type (Type) -> (Args) -> Result, so let u: (String) -> () -> String = String.uppercased gives u("x")() the value X. Initializers and key paths are passed around the same way without writing a closure: ["1", "x", "3"].compactMap(Int.init) returns [1, 3] and ["a", "bb"].map(\.count) returns [1, 2].

Map, flatMap and the "monad" pattern

You have used map on arrays: it applies a function to each element and keeps the container shape. Optional has map too, and so does Result. The pattern is the same everywhere: a container type with map lets you apply an ordinary function to the value inside, without opening the container yourself.

flatMap is the partner for steps that themselves return a container. Without it you end up with nested containers (Int??, [[Int]], Result<Result<...>>); with it, the layers are flattened. A type that has a sensible flatMap (and a way to wrap a plain value, like Optional.some or [x]) is what functional programmers call a monad. In Swift terms: it is a type for which you can chain steps that might fail, branch or carry context, while the type takes care of the plumbing.

Swift The same pattern on Optional, Array and Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

For the three Optional inputs the output is 30 adult, 30 years, 12 rejected and abc rejected: the chain stops at the first nil and never runs the later steps. The nested example parses "5", which is not an adult. With map the result is a doubly wrapped Int?? that prints as Optional(nil): the outer optional is "the parse worked" and the inner one is "the check failed". With flatMap you get a plain nil, which is what you almost always want. That line is Optional(nil) nil. For arrays, map yields 2 inner arrays while flatMap yields 5 words, so the next line prints 2 5, and the one after prints [1, 10, 2, 20, 3, 30]. The Result chain prints 16 success(4.0), -4 failure(binary.InputError.negative(-4)) and x failure(binary.InputError.notANumber("x")).

Three important things are going on:

  • Short-circuiting. On the first failure (nil or .failure), the rest of the chain is skipped without any if or guard in your code.
  • Types document the possibilities. Result<Double, InputError> tells the caller exactly what can go wrong.
  • Each step is a small pure function that you can test alone.

Compare this with the ladder of guard let statements you would write in imperative style (guard). Swift programmers often prefer guard and throws because they read top to bottom and give better stack traces, and that is a perfectly good choice. The functional chain shines when the steps are already functions, when you build the chain from parts, or when you want to keep the failure as a value instead of unwinding. See Result type and Typed throws for how the two worlds connect.

Building your own: a type with map and flatMap

Any type can join the club. A small Logged type carries a value together with a log of what happened to it. Each step returns its own log, and flatMap concatenates the logs, so the plumbing never shows up in the steps themselves:

Swift A Logged type with map and flatMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is answer: 5: starting from 20, halving gives 10, incrementing gives 11, and halving again gives 5 (integer division). The log reads ["start", "halved 20", "incremented 10", "halved 11"]. The last three lines print true three times. Those lines are the three laws every well-behaved flatMap should satisfy: wrapping a value and then chaining is the same as just calling the function (left identity), chaining with the wrapper changes nothing (right identity), and grouping the steps differently does not change the result (associativity). The standard library's Optional, Array and Result obey them, and that predictability is what makes chains safe to refactor.

Memoization: caching pure functions

Because a pure function always returns the same result for the same input, you can remember results and skip repeated work. A memoize function wraps any function with a dictionary cache. The cache lives in the closure's captured state, so the wrapper itself looks like an ordinary function:

Swift Memoizing a pure function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

fast(9) runs slowSquare once; the three calls give 81 81 81 and the call for 4 gives 16, so the first line is 81 81 81 16 and the counter line reports underlying calls: 2. The recursive Fibonacci with an inout memo prints 23416728348467685; without the cache the same recursion would need far more calls than any computer could finish.

Memoization is only valid for pure functions. Caching a function that reads the clock or a database returns stale answers. Also remember that the cache grows without bound; for long-running programs use a size limit or an actor-protected cache (Actors). The memoized closure above is not thread safe, which is fine for a single-threaded script, and Swift 6 will tell you when a closure like this crosses an isolation boundary.

Pitfalls and when to stay imperative

  • Readability first. A chain of five flatMaps with $0 everywhere is harder to read than three guard lines. Name your steps, or break the chain.
  • Closures allocate. Composed closures capture values and may allocate on the heap. In a hot loop, a plain for loop on an array is often faster than a long lazy chain. Measure before you optimize (Performance Tips).
  • No guaranteed tail calls. Deep recursion can overflow the stack even in a pure style (Recursion). Use loops or an explicit stack for very deep inputs.
  • Retain cycles. A closure that captures self and is stored on self leaks. Use [weak self] where needed (ARC).
  • Mixing styles is fine. Swift's strength is that you can write the pure core in a functional way and the shell in a straightforward imperative way.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which function is pure?

    area depends only on its arguments and has no side effects. The others change global state, read the clock or print.
  2. 2. What is the difference between map and flatMap on an Optional?

    With map, a transform returning Int? produces Int??. With flatMap the two layers are flattened into one Int?.
  3. 3. Given let f: (Int) -> Int and let g: (Int) -> String, what does f >>> g (the composition operator from the lesson) produce?

    >>> feeds the result of the left function into the right one, so the type is (Int) -> String.
  4. 4. What is currying?

    A curried function (A, B) -> C becomes (A) -> (B) -> C, which makes partial application easy.
  5. 5. Why must a memoized function be pure?

    If the function reads changing state or performs effects, replaying a cached answer skips those effects or returns stale data.

Summary

  • A pure function depends only on its arguments and has no side effects; push state and effects to the edges of the program.
  • Structs, let and copy-on-write collections make immutable styles cheap in Swift; sorted() returns a new value, sort() mutates.
  • Functions are values: store them, return them, pass them, and compose them with a small >>> operator or plain chaining.
  • Currying turns (A, B) -> C into (A) -> (B) -> C; closures that capture arguments give you partial application directly.
  • map applies a function inside a container, flatMap chains steps that return containers (Optional, Array, Result and your own types); well-behaved flatMaps satisfy the monad laws.
  • Memoize only pure functions, and bound the cache.
  • Prefer clarity: use guard and throws when they read better, and measure before optimizing closure-heavy code.

Next: Designing Good APIs