Scoped APIs & readability patterns
Apply scoped APIs and naming patterns for DSLs: namespace tokens, group with helpers, and keep blocks small and explicit.
Why scope a DSL?
Readable DSLs limit what you can do in a block and name things clearly. Use namespaces, small helpers, and grouping to keep intent obvious.
Namespace pattern
Placing tokens under R narrows the surface and prevents clashes with app symbols; calls stay short and scannable.
struct Route { let method: String; let path: String }
// Namespace instead of global free functions
enum R {
static func GET(_ path: String) -> Route { Route(method: "GET", path: path) }
static func POST(_ path: String) -> Route { Route(method: "POST", path: path) }
}
@resultBuilder
struct RoutesBuilder {
static func buildBlock(_ parts: Route...) -> [Route] { parts }
}
func routes(@RoutesBuilder _ content: () -> [Route]) -> [Route] { content() }
let table = routes {
R.GET("/home")
R.POST("/upload")
}
for r in table { print("\(r.method) \(r.path)") }All lessons in this course
- Building mini-DSLs with result builders
- Scoped APIs & readability patterns
- Practical examples without UI frameworks