Swift中非文字值的枚举

前端之家收集整理的这篇文章主要介绍了Swift中非文字值的枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法将像字典元组这样的非文字值映射到枚举?以下代码将为枚举抛出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时,语言参考明确指出:

the 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
}
原文链接:/swift/319432.html

猜你在找的Swift相关文章