Default value for Enum in Swift

前端 未结 11 1852
南旧
南旧 2020-12-31 07:30

I have an enum :

public enum PersonType:String {

 case Cool                       = \"cool\"
 case Nice                       = \"rude\"
 case          


        
11条回答
  •  醉梦人生
    2020-12-31 07:48

    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
    

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

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

提交回复
热议问题