Nonfailable enum initializer with default value
Asked Answered
C

1

6

Is there a way to define an enum, when initialized from rawValue will default to some value instead of failing? Useful in cases where the value may be unexpected (i.e. server API errors)

Caitiff answered 4/6, 2015 at 2:31 Comment(2)
Can't you just override that init that takes the rawValue argument...? And return super.init(rawValue: rawValue) ?? yourDefaultValue?Germiston
...but if the value may be unexpected, an enum might be the wrong avenue... or failure might be what you want...Germiston
A
5

You mean something like that?

enum ErrorCode: Int {
    case NoErr = 0, Err1, Err2, LastErr, DefaultErr

    init(value: Int) {
        if (value > LastErr.rawValue) {
            self = .DefaultErr
        } else {
            self = ErrorCode(rawValue: value)!
        }
    }
}

let error: ErrorCode = .LastErr
let anotherError: ErrorCode = ErrorCode(value: 99)

Here is another variation:

enum ErrorCode: Int {
    case NoErr = 0, Err1, Err2, LastErr

    init?(value: Int) {
        if (value > 3) {
            return nil
        } else {
            self = ErrorCode(rawValue: value)!
        }

    }
}

let error: ErrorCode = .LastErr
let anotherError: ErrorCode? = ErrorCode(value: 99)

which is equivalent to :

enum ErrorCode: Int {
    case NoErr = 0, Err1, Err2, LastErr
}

let anotherError: ErrorCode? = ErrorCode(rawValue: 99)

because as Apple doc is stating:

NOTE

The raw value initializer is a failable initializer, because not every raw value will return an enumeration member. For more information, see Failable Initializers.

But in general, if you want to use enum with rawvalue, you should expect an optional and treat the nil returned value as a default error case outside the enum definition. That would be my recommendation.

Alake answered 4/6, 2015 at 3:35 Comment(1)
Yes, it is probably better to expect nil value, but I opted for your solution for sake of convenienceCaitiff

© 2022 - 2024 — McMap. All rights reserved.