Swift中非文字值的枚举

Swift中非文字值的枚举,第1张

概述有没有办法将像字典元组这样的非文字值映射到枚举?以下代码将为枚举抛出Raw值必须是文字. enum FileType { case VIDEO = ["name": "Video", "contentTypeMatcher": "video/"] case IMAGE = ["name": "Image", "contentTypeMatcher": "image/"] c 有没有办法将像字典元组这样的非文字值映射到枚举?以下代码将为枚举抛出Raw值必须是文字.
enum fileType {    case VIDEO = ["name": "VIDeo","ContentTypeMatcher": "vIDeo/"]    case IMAGE = ["name": "Image","ContentTypeMatcher": "image/"]    case AUdio = ["name": "Audio","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 AUdio  = (name: "Audio",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中非文字值的枚举全部内容,希望文章能够帮你解决Swift中非文字值的枚举所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1035682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存