0Pricing
Swift Academy · Lesson

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

  1. Building mini-DSLs with result builders
  2. Scoped APIs & readability patterns
  3. Practical examples without UI frameworks
← Back to Swift Academy