Swift中Enum的默认值 [英] Default value for Enum in Swift

查看:738
本文介绍了Swift中Enum的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

public enum PersonType:String {

 case Cool                       = "cool"
 case Nice                       = "rude"
 case SoLazy                     = "so-lazy"

 public var description: String {
    switch self {
    case .Cool:
        return "Cool person"
    case .Nice:
        return "Nice person"
    case .SoLazy:
        return "its so lazy person"
    }
}


 public var typeImage: String {
    switch self {
    case .Cool:
        return "cool.png"
    case .Nice:
        return "img_nice.png"
    case .Solazy:
        return "lazy.png"
    }
   }  

}

问题我不知道所有人的类型键,所以我需要处理类型为人的默认情况,并给它描述将是它的关键像so-lazy和默认图像。

The problem I don't know all the person type keys so I need to handle a default case of type person and to give it the description will be it's key like "so-lazy" and a default image.

假设我从网络服务获得此结果:

let's say I get this result from the web service:

[
    {
        name: "john",
        key: "cool"
    },
    {
        name: "paul",
        key: "funny"
    }
]

我需要一个默认情况来处理密钥有趣的

I need to have a a default case to handle the key "funny"

这是我在解析和创建人物对象时如何初始化我的枚举:

here is how I init my enum while parsing and creating person object:

if let personType = PersonType(rawValue:personTypeKey ?? "") {
   self.personType = personType
}

我想要一个 else 或更好的方法来处理枚举中未知密钥的情况,并为其提供密钥作为描述和默认图像。

I want an else or a better approach to handle the case of unknown keys in my enum, and give them the key as description and a default image.

推荐答案

另一种适用于Swift 3的方法(可能是2,不知道):

Another approach that works in Swift 3 (maybe 2, don't know):

enum PersonType: String {
    case cool = "cool"
    case nice = "nice"
    case soLazy = "so-lazy"
    case other
}

let person = PersonType(rawValue: "funny") ?? .other

在这种情况下,person变量的类型为PersonType.other。

The person variable is of type PersonType.other in this case.

这样做的缺点是你不知道.other案例的原始字符串值。

The downside to this is that you don't know the raw string value of the .other case.

这篇关于Swift中Enum的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆