Default value for Enum in Swift

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

    Try this approach.

    public enum PersonType:String {
    
        case Cool                       = "cool"
        case Nice                       = "rude"
        case SoLazy                     = "so-lazy"
    
        static let allKeys = [Cool.rawValue, Nice.rawValue, SoLazy.rawValue]
    }
    
    extension PersonType
    {
        func description(personTypeKey : String) -> String {
    
            if PersonType.allKeys.contains(personTypeKey)
            {
                switch self {
                case .Cool:
                    return "Cool person"
                case .Nice:
                    return "Nice person"
                case .SoLazy:
                    return "its so lazy person"
                }
            }
            else
            {
                return "YourTextHere"
            }
        }
    
        func typeImage(personTypeKey : String) -> String {
    
            if PersonType.allKeys.contains(personTypeKey)
            {
                switch self {
                case .Cool:
                    return "cool.png"
                case .Nice:
                    return "img_nice.png"
                case .SoLazy:
                    return "lazy.png"
                }
            }
            else
            {
                return "YourImageHere"
            }
        }
    }
    

提交回复
热议问题