How to create a useful helper for using both Color and UIColor in one project?

47 Views Asked by At

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)
2

There are 2 best solutions below

0
Geoff Hackworth On

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:

extension UIColor {
    static var appBlack = UIColor(hex: "#000814") 
}

extension Color {
    static var appBlack = Color(UIColor.appBlack)
}

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.

0
lorem ipsum On

You can use UIColor as a single source of truth with a func in Color.

extension UIColor {
    static var appBlack: UIColor  = {
        return UIColor(hex: #000814)
    }()
}

extension Color{
    static func fromUIColor(_ color: UIColor) -> Color{
        Color(uiColor: color)
    }
}

Then you can use.

Color.fromUIColor(.appBlack)