2016-03-03 73 views
0

我想不出一种方法来从便利初始化中的嵌套枚举中检索原始值。 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) 
+0

你试图通过嵌套像这样的枚举来实现什么? – ColGraff

+0

嵌套枚举提供更好的自动完成结果。 – efremidze

+0

@efremidze强制unwrap像self.init(...)!是我见过的最糟糕的想法。 – user3441734

回答

0

这是最简单的替代实现:

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) 
3

我有一个稍微不同的方法,你可以采取,但会使使用字体一样容易。首先,您需要为您的字体枚举的协议,然后扩展到提供一个默认的方法,这样的:

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) 
+0

使用这样的协议是我的选择 – efremidze

相关问题