Better Programming

Advice for programmers.

Follow publication

Member-only story

Using Swift’s Type System To Model Behaviour

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) {

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Manuel Meyer
Manuel Meyer

Written by Manuel Meyer

Freelance Software Developer and Code Strategist.

Write a response