In a project that I am working on both Swift and SwiftUI are used. I want to use a helper that returns the color. but under the current circumstances I have two helpers which are kind of duplicated. I could not come up with an idea so far to unify this or solve in another way. Does anybody have a similar problem and idea for good practice?
The current situation is similar to follows;
extension UIColor {
static var appBlack: UIColor {
return UIColor(hex: #000814)
}
}
extension Color {
static var appBlack: Color {
return Color(UIColor.appBlack)
}
}
with this approach, I can create a color just by;
let appColor: Color = .appBlack
Another approach is using UIColor extension also for Color, but in this case, you need to create the color as follows, removing init is not possible;
let appColor: Color = .init(.appBlack)
As @matt said in a comment, you are dealing with two separate types so can’t really unify the code (other than perhaps using a code generation tool to create both extensions from a single source). You are already avoiding duplicating the actual color definitions so the two versions will always be in sync. The only minor improvement I might suggest is to simplify the code slightly:
This is shorter and only calculates each color the first time it is used so will be slightly faster. These are lazy properties instead of the computed properties used in the original code.