将更多数据嵌入到枚举案例中

Embed more data into enum cases

我有以下叠层枚举。

public enum Icons {
    public enum Arrow: String {
        case Angle1 = "\u{f100}"
        case Angle2 = "\u{f101}"
        case Angle3 = "\u{f102}"
        case Angle4 = "\u{f103}"
        case ArrowBottomLeft = "\u{f104}"
        case ArrowBottomRight = "\u{f105}"
    }

    public enum Clothing: String {
        case BallCap = "\u{f100}"
        case Belt = "\u{f101}"
        case Boot = "\u{f102}"
        case BowTie = "\u{f103}"
    }

    public enum Emotions: String {
        case Angel = "\u{f100}"
        case AngrySick = "\u{f101}"
        case Angry = "\u{f102}"
        case Bitter = "\u{f103}"
        case Concerned = "\u{f104}"
        case Cool = "\u{f105}"
    }
}

我有大量图标我想集成到我的应用程序中。我还有一个 UIImage 扩展初始化程序,它将 UIFont 作为参数和要绘制的图标的字符串(源自 Icons.Category.Icons - 请注意,在这种情况下,类别是箭头、服装或情绪)。

要获取图标,我调用:

let image = UIImage(  
                      fromIcon: Icons.Emotions.Angel.rawValue, 
                      withFont: UIFont.iconFontAngel(22)
                   )

三种类型的图标中的每一种都有关联的 UIFont 扩展名:

我怎样才能更好地声明图标以包含 UIFont、字体大小和其他特定于类别的选项,因为我确切地知道每个类别对应的 UIFont 并且我只需要传递一个参数,例如 Icons.Arrow.Angle3 到 UIImage 初始值设定项并从此参数中提取字符串、UIFont 和其他需要的选项?

我正在考虑将图标类型声明为已设置,但我不确定如何以干净的方式解决这个问题。

不要为此使用枚举。使用结构。

public struct FontBasedIcon {

    private init(string: String, fontName: String) {
        self.string = string
        self.fontName = fontName
    }

    public let string: String
    public let fontName: String

    public func font(size size: CGFloat) -> UIFont {
        return UIFont(name: fontName, size: size)!
    }

    public func image(fontSize fontSize: CGFloat) -> UIImage {
        let string = self.string as NSString
        let attributes = [ NSFontAttributeName: self.font(size: fontSize) ]
        var rect = string.boundingRectWithSize(CGSizeMake(CGFloat.infinity, CGFloat.infinity), options: .UsesLineFragmentOrigin, attributes: attributes, context: nil)
        let size = CGSizeMake(ceil(rect.width), ceil(rect.height))
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        defer { UIGraphicsEndImageContext() }
        string.drawAtPoint(CGPoint.zero, withAttributes: attributes)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}

然后将常量声明为静态属性:

public extension FontBasedIcon {
    public struct Arrow {
        public static let Angle1 = FontBasedIcon(string: "\u{f100}", fontName: "ArrowFont")
        public static let Angle2 = FontBasedIcon(string: "\u{f101}", fontName: "ArrowFont")
        // etc.
    }

    public struct Emotion {
        public static let Angel = FontBasedIcon(string: "\u{f100}", fontName: "EmotionFont")
        public static let AngrySick = FontBasedIcon(string: "\u{f101}", fontName: "EmotionFont")
        // etc.
    }
}

用法:

let angelImage = FontBasedIcon.Emotion.Angel.image(fontSize: 22)