I have a design system project where multiple Apps import the design system. This presents a few problems:
- For SwiftUI previewing, it makes the most sense to provide a default set of colors. This keeps things light weight and flexible.
- Optionally, each app importing the Design System should be able to override one of these colors. The goal is to provide a turn key starter kit for tons of apps and prototypes and only override things when needed.
- I'd like the design system to be as automated as possible, were the Swift Package does all the work to set up the rules and definitions. The presence of a named color in the Assets file of the App target creates an override. Why? Using Swift Package plugins to generate code from the assets folder is ideal.
I've had mixed results trying to localize assets. I've also tried to inspect the Bundle names but this felt fragile and less elegant. I came up with the solution below where if a color is present in the main bundle (the App) then use it otherwise fall back to the Swift Package .module. This uses UIKit to check if the image is present but that feels like a hack.
Sample code below shows the logic for checking if an image is present in the main bundle.
import SwiftUI
import UIKit
extension Color {
// Auto generate this in the future using a SPM plugin.
public enum Palette: String, CaseIterable {
case brand, error, warning, success
}
public static func designSystem(color: Palette) -> Color {
let hasOverride = UIColor(named: color.rawValue) != nil
let bundle: Bundle = hasOverride ? .main : .module
return self.init(color.rawValue, bundle: bundle)
}
}
The screenshot shows this behavior in action.
Is there is a better or "more official" way to accomplish this kind if override across a hierarchy of App targets and Swift Package resources? It seems heavy handed to import all of UIKit to do this, but it works. I have been unable to get localized colors to accomplish the same thing.
![[![enter image description here[]
[1]: https://i.stack.imgur.com/ltt1c.jpg](https://i.stack.imgur.com/JMXdL.jpg)