简体   繁体   中英

Default value for Enum in Swift

I have an 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"
    }
   }  

}

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 aa 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
}

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.

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.

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.

This goes pretty close but I would like to be able to store the value that can be associated with it, kind of like you can with C.

enum Errors: Int {
    case transactionNotFound = 500
    case timeout = -1001
    case invalidState = 409
    case notFound = 404
    case unknown

    init(value: Int) {
        if let error = Errors(rawValue: value) {
            self = error
        } else {
            self = .unknown
        }
    }
}

Errors(value: 40) // .unknown
Errors(value: 409) // .invalidState
Errors(value: 500) // .transactionNotFound

Had to create a custom initializer, otherwise it is recursive. And it is still possible to create using the rawValue initializer by accident.

This however feels more Swifty, I removed the : Int type specifier which allows you to use associated values, now the exceptional case that we don't do anything special is handled in the other :

enum Errors2 {
    case transactionNotFound
    case timeout
    case invalidState
    case notFound
    case other(Int)

    init(rawValue: Int) {
        switch rawValue {
        case 500:
            self = .transactionNotFound
        case -1001:
            self = .timeout
        case 409:
            self = .invalidState
        case 404:
            self = .notFound
        default:
            self = .other(rawValue)
        }
    }
}

Errors2(rawValue: 40) // .other(40)
Errors2(rawValue: 409) // .invalidState
Errors2(rawValue: 500) // .transactionNotFound
Errors2(rawValue: -1001) // .timeout

With this I could get the actual value for an "other" error, and I can use the rawValue so it acts a lot like an Int based enum. There is the single case statement to map the names but from then on you can use the names and never need to refer to the numbers.

like so:

init() {
    self = .Cool
}

In Swift 5.1 it's now possible to set default values. Your code would look like this:

enum PersonType {
  case cool(String = "cool")
  case nice(String = "rude")
  case soLazy(String = "so-lazy")
}

This question is pretty old now and a lot has moved on in the Swift world. With Swift 5 I would recommend the approach below which involves creating a new initializer for the enum:

public enum PersonType:String, ExpressibleByNilLiteral {

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

    public init(nilLiteral:()) {
        self = .SoLazy
    }

    public init!(_ optionalValue:RawValue?) {
        guard let rawValue = optionalValue,
              let validValue = PersonType(rawValue:rawValue) else {
            self = .SoLazy
            return
        }
        self = validValue
    }

    public var description: String {
        switch self {
        case .Cool return "Cool Person"
        //... etc
        }
    }

    public var typeImage: String {
        switch self {
        case .Cool return "cool.png"
        //... etc
        }
    }
}

Use it like this:

self.personType = PersonType(personTypeKey)

Or like this:

self.personType = nil

In either case, even if the value isn't valid for the PersonType enum or it's just nil you will get a valid enum that's set to the default value of .SoLazy

This is similar to several other approaches in this thread but instead of listing out all the possible valid values (which can be unwieldy if there are a lot of them) it uses a multiple guard let = statement to guarantee it works.

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"
        }
    }
}

For you case:

Default Value of Enum : I just add an default computed property, Or include an customize init.

public enum PersonType:String {

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

    /// add a `default` computer property
    public static var `default`: PersonType {
        return .SoLazy
    }

    /// add an customize init function 
    public init(person: String? = nil) {
        if let person = person {
            switch person {
            case "cool": self = .Cool
            case "rude": self = .Nice
            case "so-lazy": self = .SoLazy
            default: self = .SoLazy
            }
        } else {
            self = .SoLazy
        }
    }

    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"
        }
    }

}

To use:

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

Or

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

Default Value of Enum With Associated Value:

public enum Gender {
    case man
    case woman
}

public enum PersonType {

    case cool(Gender)
    case nice(Gender)
    case soLazy(Gender)

    public static var `default`: PersonType {
        return PersonType.make.soLazy()
    }

    public enum Builder {
        public static func cool() -> PersonType {
            return PersonType.cool(.woman)
        }
        public static func nice() -> PersonType {
            return PersonType.nice(.woman)
        }
        public static func soLazy() -> PersonType {
            return PersonType.soLazy(.woman)
        }
    }

    public static var make: PersonType.Builder.Type {
        return PersonType.Builder.self
    }


    public var description: String {
        switch self {
        case .cool(let gender):
            switch gender {
            case .man: return "Cool boy"
            case .woman: return "Cool girl"
            }
        case .nice(let gender):
            switch gender {
            case .man: return "Nice boy"
            case .woman: return "Nice girl"
            }
        case .soLazy(let gender):
            switch gender {
            case .man: return "its so lazy boy"
            case .woman: return "its so lazy girl"
            }
        }
    }

    public var typeImage: String {
        switch self {
        case .cool(_):
            return "cool.png"
        case .nice(_):
            return "img_nice.png"
        case .soLazy(_):
            return "lazy.png"
        }
    }

}

To use:

let onePersonType = PersonType.default
let anotherPersonType = PersonType.make.soLazy()

The second case solution I was found on Ilya Puchka' blog . And also it's mentioned in swift's proposal .

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)

I recommend using such an approach

public enum Result {
    case passed(hint: String)
    case failed(message: String)

    static let passed: Self = .passed(hint: "")
}


let res: Result = Result.passed

I wonder if dictionary is not a better fit than enum here:

let dict = [
    "Cool": "cool",
    "Nice": "rude",
    "SoLazy": "so-lazy"
]

let personType = "unknown"
let personDescription = dict[personType] ?? "Unknown"

Less typing, faster processing, more natural handling of the default case, easier to expand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM