Member-only story
Using Swift’s Types as Domain-Specific Languages
How to use Swift’s Types to create modules — Datatypes, UseCases, Features — that will be controlled through a vocabulary defined by their Domain Specific Languages (DSL)
As these vocabularies are finite sets, this kind of coding has proven to enable the coding of even complex domains in simple fashions and in very little time — think hours, whereas conventional coding needs weeks.
DSL Interfaced Datatypes
Let’s start with a simple model datatype — a counter that increments and decrements a value.
struct Counter {
enum Change {
case increment
case decrement
}
func alter(_ c:Change) -> Self {
switch c {
case .increment: return Self(value:value+1)
case .decrement: return Self(value:value-1)
}
}
let value: Int
}
The type Counter.Change
is this module’s DSL. Its vocabulary knows two words: increment and decrement.
The alter method takes a DSL value, checks if the value is increment or decrement, and returns a new Counter
object with the value being changed accordingly.
var c = Counter(value:0)
c =…