在扩展名swift中使用enum作为字符串

时间:2017-02-06 05:27:18

标签: swift swift3

我在我的app中为我的所有font-family声明了一个枚举。现在我想在UIFFont的函数中用作字符串,但它导致错误!

enum Family: String {
    case SansLight = "SansMobile-Light"
    case SansReqular = "SansMobile"
    case SansMedium = "SansMobile-Medium"
}

extension UIFont {
    class func systemFontOfSize(size: CGFloat) -> UIFont {
        return UIFont(name: Family.RawValue, size: size)
    }
}

我得到的错误:

Cannot convert value of type 'Family.RawValue.Type' (aka 'String.Type') to expected argument type 'String'

如何使用单个函数在上面的UIFont中使用枚举?

2 个答案:

答案 0 :(得分:2)

你必须写

   enum Family: String {
        case SansLight = "SansMobile-Light"
        case SansReqular = "SansMobile"
        case SansMedium = "SansMobile-Medium"
    }

    extension UIFont {
        class func systemFontOfSize(size: CGFloat) -> UIFont {
            return UIFont(name: Family.SansLight.rawValue, size: size)
        }
    }

答案 1 :(得分:1)

您忘记访问自case enum添加的Family

应该是

Family.SansLight.rawValue // OR Family.SansReqular.rawValue OR Family.SansMedium.rawValue

//So it goes like 
return UIFont(name: Family.SansLight.rawValue, size: size)

不直接

Family.RawValue

注意: init(name:size:)将返回可选的UIFont?实例,因此您需要将其解包,因为在您的函数中,您已指定返回类型为UIFont而不是{ {1}}。