Member-only story

Union Types in Swift

Are you still wondering how to implement algebraic types using the Swift programming language?

Nikita Lazarev-Zubov
3 min readJul 5, 2024

Not long time ago I came across a question on Stack Overflow, where someone asked if there’s a possibility in Swift to implement an algebraic sum type for a function return type, something in the form of Type1 | Type2. In programming languages with weaker type systems, like Python, there usually are ways of declaring something like Union[Type1, Type2] — a union of two or more types, which actually stores only one of them after evaluation of the expression.* But what can Swift offer to you instead?

*Strictly speaking, since Python has a dynamic type system, there’s no need for such a thing as the Union actual type. What we have there is an optional type hint that can help with type safety at the compile time, but has no influence on the interpreter of the run time.

Let’s look at how you could use such an opportunity within the language.

Exactly One of a Limited Amount of Options

Let’s theorise a little bit. What if Swift had the syntax as in the snippet below?

func returnValue() -> (String | Int) {
// ...
}
let result = returnValue()

--

--

Nikita Lazarev-Zubov
Nikita Lazarev-Zubov

Written by Nikita Lazarev-Zubov

Swift and general programming topics, Agile software development, soft skills

No responses yet