Created
December 18, 2021 03:46
-
-
Save IanKeen/b7ea8afabd3dcdd08dd8b7ab699fb4dd to your computer and use it in GitHub Desktop.
Namespace and Implicit member chains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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