Better Programming

Advice for programmers.

Member-only story

Using Swift’s Type System To Model Behaviour

Create fully immutable types for your domain using Swift

Manuel Meyer
Better Programming
Published in
14 min readFeb 28, 2023

--

Photo by Luke Chesser on Unsplash

I want to demonstrate how we can use Swift’s type system to efficiently and effectively model and implement behavior. The emerging code is easy to read, as they resemble spoken English to a high degree. And the fact that each module exposes one method makes them simple to test and integrate. The code can be fully immutable — eliminating many sources for possible bugs. If it can’t change on purpose, it can’t change accidentally.

Let’s imagine a to-do list app.

A to-do task might contain a title, a longer description, or a creation date. It might be finished or unfinished. Conventionally, this would be modelled with mutable properties.

But we can create fully immutable types for our domain using Swift's sophisticated type system.

struct TodoTask {
enum Change {
case title(to:String)
case description(to:String)
case finish
case unfinish
}
enum State {
case unfinished
case finished
}
// members
let id : UUID
let title : String
let description: String
let state : State
let created : Date
// initialisers
init(title:String) {…

--

--

Manuel Meyer
Manuel Meyer

Written by Manuel Meyer

Freelance Software Developer and Code Strategist.

Responses (1)