Swift 优雅的 Enum

声名 Enum

enum Color {
    static func RGB(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor? {
        UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
    }
    static func RGBA(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor? {
        UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
    }
    static func Hex(hex: String) -> UIColor? {
        //....
    }
}

使用 Enum

Color.RGB(r: 155, g: 155, b: 155)

Color.RGBA(r: 155, g: 155, b: 155, a: 0.5)

声名 嵌套 Enum


enum R {
    enum string: String {
        case add = "添加"
    }
    enum image: String {
        case logo = "logo"
    }
}
extension UIImage {
    convenience init?(r: R.image) {
        self.init(named: r.rawValue)
    }
}

extension UIButton {
    func setTitle(r: R.string, for state: UIControl.State){
        self.setTitle(r.rawValue, for: state)
    }
}

使用 嵌套 Enum

// 图片使用
let image: UIImage? = UIImage(r: R.image.logo)

// 按钮使用
let btn: UIButton? = UIButton()
btn?.setTitle(r: R.string.add, for: .normal)
posted @ 2024-08-08 21:49  IT_IOS_MAN  阅读(12)  评论(0编辑  收藏  举报