Swift extension and enum for color schemes

2020-07-30 03:03发布

问题:

I create enum in blank swift file for manage color Schemes in my App with this block of code:

enum Color {
    case border
    case waterMelon
    case bleu
    case ufoGreen
    case lightBlue 
}

In the bottom of that I created a extension base on Color enum I just made.

Here the extension:

extension Color {
    var value: UIColor {
        var instanceColor = UIColor.clear

        switch self {
        case .border:
            instanceColor = UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
        case .waterMelon:
            instanceColor = UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
        default:
            instanceColor = UIColor.clear
        }

        return instanceColor

    }
}

Now the problem is when I wanna use those color I should used something like this:

//now : I don't like it.
view.backgroundView = Color.dark.value

//that how I want to be
view.backgroundView = Color.dark

// or like this
view.backgroundView = .dark

And I know it's because of the value that i declare on extension . but how can I get rid of that?

回答1:

Don't use an enum then. If you don't want to enumerate on the values in a switch statement, there is no need for an enum. Use a struct with constant attributes.

struct Color {
    static let border = UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
    static let waterMelon = UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
    // and so on ....
}

If you want to extend UIColor to have access to all the other colors of UIColor as well, you can extend UIColor like this:

extension UIColor {
    static var border: UIColor {
        return UIColor(red:0.92, green:0.93, blue:0.94, alpha:1.00)
    }

    static var waterMelon: UIColor {
        return UIColor(red:0.97, green:0.38, blue:0.45, alpha:1.00)
    }
}


标签: ios swift swift3