有没有办法将像字典元组这样的非文字值映射到枚举?以下代码将为枚举抛出Raw值必须是文字.
enum FileType { case VIDEO = ["name": "Video","contentTypeMatcher": "video/"] case IMAGE = ["name": "Image","contentTypeMatcher": "image/"] case AU@R_403_410@ = ["name": "Au@R_403_410@","contentTypeMatcher": "aduio/"] case PDF = ["name": "PDF","contentTypeMatcher":"application/pdf"] case TEXT = ["name": "Text","contentTypeMatcher": "text/"] case FOLDER= ["name": "Folder","contentTypeMatcher" :"application/x-directory"] case PLAIN = ["name": "Plain","contentTypeMatcher": ""] }
当我使用元组时,它是一样的:
enum FileType { case VIDEO = (name: "Video",contentTypeMatcher: "video/") case IMAGE = (name: "Image",contentTypeMatcher: "image/") case AU@R_403_410@ = (name: "Au@R_403_410@",contentTypeMatcher: "aduio/") case PDF = (name: "PDF",contentTypeMatcher:"application/pdf") case TEXT = (name: "Text",contentTypeMatcher: "text/") case FOLDER = (name: "Folder",contentTypeMatcher :"application/x-directory") case PLAIN = (name: "Plain",contentTypeMatcher: "") }
在谈到
Enumeration Declaration时,语言参考明确指出:
原文链接:/swift/319432.htmlthe raw-value type must conform to the Equatable protocol and one of the following literal-convertible protocols: IntegerLiteralConvertible for integer literals,FloatingPointLiteralConvertible for floating-point literals,StringLiteralConvertible for string literals that contain any number of characters,and ExtendedGraphemeClusterLiteralConvertible for string literals that contain only a single character.
除了文字之外别无其他可以用作原始值.
一种可能的解决方法是将字典表示为字符串 – 例如,您可以使用逗号分隔元素,使用冒号来键入值:
enum FileType : String { case VIDEO = "name:Video,contentTypeMatcher:video/" case IMAGE = "name:Image,contentTypeMatcher:image/" ... }
var dictValue: [String : String] { var dict = [String : String]() var elements = self.rawValue.componentsSeparatedByString(",") for element in elements { var parts = element.componentsSeparatedByString(":") if parts.count == 2 { dict[parts[0]] = parts[1] } } return dict }