Sitemap
Better Programming

Advice for programmers.

Member-only story

The Ultimate Domain Language: Declarative Swift

21 min readNov 17, 2022

--

Photo by Solaiman Hossen on Unsplash

I want to introduce you to Declarative Swift — a coding style that allows us to efficiently and effectively create domain-driven code that is easy to verify. Writing code like this has proven to be faster than conventional coding, while it offers less room for bugs to hide in.

Domain Examples

Let’s start with a simple example: a todo list.

The following code block contains a datatype for todo items and todo lists:

struct TodoItem:Identifiable {
enum Change {
case title (to:String)
case due (to:TodoDate)
case location(to:Location)
case finish
case unfinish
}
// members
let id : UUID
let title : String
let completed: Bool
let created : Date
let due : TodoDate
let location : Location

// initialisers
init(title:String) { self.init(UUID(),title,false,.unknown, Date(),.unknown) }
private
init(_ i:UUID,_ t:String,_ c:Bool,_ d:TodoDate,_ cd:Date,_ l:Location) { id=i; title=t; completed=c; due=d; created=cd; location=l }

func alter(_ c:Change...) -> Self { c.reduce(self) { $0.alter($1) } }
private
func alter(_ c:Change ) -> Self {
switch c {
case…

--

--

Responses (1)