Member-only story
Using Swift’s Type System To Model Behaviour
Create fully immutable types for your domain using Swift
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) {…