Default value for Enum in Swift

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

    To answer your question:

    public enum PersonType:String {
    
        case Cool                       = "cool"
        case Nice                       = "rude"
        case SoLazy                     = "so-lazy"
        static var `default`: PersonType { return .SoLazy }
    
        public init(rawValue: RawValue) {
            switch rawValue {
            case PersonType.Cool.rawValue: self = .Cool
            case PersonType.Nice.rawValue: self = .Nice
            case PersonType.SoLazy.rawValue: self = .SoLazy
            default: self = .default
            }
        }
    
        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"
            }
        }
    
    }
    

    Now since having no failable initializer with default value replace your:

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

    With:

    personType = PersonType(rawValue: personTypeKey)
    

提交回复
热议问题