Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nonfailable enum initializer with default value

Tags:

enums

swift

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)

like image 527
Morrowless Avatar asked Jun 04 '15 02:06

Morrowless


People also ask

Do enums have default values?

The default value of an uninitialized enumeration, just like other value types, is zero. A non-flags-attributed enumeration should define a member that has the value of zero so that the default value is a valid value of the enumeration.

Can an enum have an initializer?

Enums can provide their own initializer to provide the initial case with a value or can be extended or conform to protocols.

What is raw value in Swift?

Raw Values You can use Strings, Characters or even Floats instead. If you want to use the three-letter IATA code as the backing value of the enum cases you can do that: Whatever the type you choose, the value you assign to a case is called a rawValue .


1 Answers

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.

like image 82
John Difool Avatar answered Sep 17 '22 07:09

John Difool