Skip to content

Instantly share code, notes, and snippets.

@IanKeen
Created December 18, 2021 03:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanKeen/b7ea8afabd3dcdd08dd8b7ab699fb4dd to your computer and use it in GitHub Desktop.
Save IanKeen/b7ea8afabd3dcdd08dd8b7ab699fb4dd to your computer and use it in GitHub Desktop.
Namespace and Implicit member chains
// 1. Create a generic namespace we can ue to 'hang' values off
public struct Namespace<Base> { }
// 2. Add a namespace to a type(s) with the desired name
extension Color {
public static var theme: Namespace<Self> { .init() }
}
extension Font {
public static var theme: Namespace<Self> { .init() }
}
// 3. Add values to the namespaces
extension Namespace where Base == Color {
public var primary: Color { .blue }
}
extension Namespace where Base == Font {
public var headline: Font { .custom("MyFont", size: 30, relativeTo: .headline) }
}
// 4. Profit! (Enjoy the benefits of both namespaces and autocomplete)
Text("Foo")
.foregroundColor(.theme.primary)
.font(.theme.headline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment