Default value for Enum in Swift

前端 未结 11 2004
南旧
南旧 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:54

    Drop the raw type, and use enum with associated value:

    public enum PersonType {
        case Cool
        case Nice
        case SoLazy
        case Unknown(String)
        static func parse(s:String) -> PersonType {
            switch s {
                case "Cool" : return .Cool
                case "Nice" : return .Nice
                case "SoLazy" : return .SoLazy
                default: return Unknown(s)
            }
        }
    }
    

    The downside to dropping the raw type is that you must provide some logic for parsing the known enum values. The upside, however, is that you can fit anything else into a single Unknown case, while keeping the actual "unknown" value available for later use.

提交回复
热议问题