Default value for Enum in Swift

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

    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.

提交回复
热议问题