【问题标题】:Passing a nested enum as a parameter将嵌套枚举作为参数传递
【发布时间】:2016-03-03 22:40:17
【问题描述】:

我想不出一种从便利初始化中的嵌套枚举中检索原始值的方法。 fontName.rawValue 将不起作用,因为 Custom 没有案例。有什么建议吗?

extension UIFont {
    enum Custom {
        enum Roboto: String {
            case Regular = "RobotoRegular"
        }
        enum SanFrancisco: String {
            case Semibold = "SFSemibold"
        }
    }

    convenience init?(name fontName: Custom, size fontSize: CGFloat) {
        self.init(name: fontName.rawValue, size: fontSize)
    }
}

// Example Usage
UIFont(name: .Roboto.Regular, size: 18)

【问题讨论】:

  • 你试图通过嵌套这样的枚举来实现什么?
  • 嵌套枚举提供更好的自动补全结果。
  • @efremidze 像 self.init(...) 一样强制解包!是我见过的最糟糕的主意。
  • @user3441734 是的,我同意,这只是一个例子。

标签: ios swift enums swift2 uifont


【解决方案1】:

我可以采取一种稍微不同的方法,但会使使用字体变得同样简单。首先你需要为你的字体枚举创建一个协议,然后是一个扩展来提供一个默认的方法,像这样:

protocol CustomFontsProtocol {
    var fontName: String { get }
}

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

现在,您可以像这样为您的枚举创建它:

enum CustomFonts {
    enum Roboto: CustomFontsProtocol {
        case Regular

        var fontName: String {
            switch self {
            case Regular: return "RobotoRegular"
            }
        }
    }

    enum SanFrancisco: CustomFontsProtocol {
        case Semibold

        var fontName: String {
            switch self {
            case Semibold: return "SFSemibold"
            }
        }
    }
}

这将允许你像这样调用你的字体:

CustomFonts.SanFrancisco.Semibold.size(18)

【讨论】:

  • 使用这样的协议是我的替代方案
【解决方案2】:

这是最简单的替代实现:

protocol CustomFontsProtocol {
    func size(size: CGFloat) -> UIFont?
}

extension CustomFontsProtocol where Self: RawRepresentable, Self.RawValue == String {
    func size(size: CGFloat) -> UIFont? {
        return UIFont(name: rawValue, size: size)
    }
}

enum CustomFonts {
    enum Roboto: String, FontConvertible {
        case Regular = "RobotoRegular"
    }
    enum SanFrancisco: String, FontConvertible {
        case Semibold = "SFSemibold"
    }
}

// Example Usage
CustomFonts.SanFrancisco.Semibold.size(18)

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多