Get associated value from enumeration without switch/case

There are actually multiple ways to do it.

Let’s do it by extending your enum with a computed property:

enum X {
    case asInt(Int)
    case asDouble(Double)

    var asInt: Int? {
        // ... see below
    }
}

Solutions with if case

By having let outside:

var asInt: Int? {
    if case let .asInt(value) = self {
        return value
    }
    return nil
}

By having let inside:

var asInt: Int? {
    if case .asInt(let value) = self {
        return value
    }
    return nil
}

Solutions with guard case

By having let outside:

var asInt: Int? {
    guard case let .asInt(value) = self else {
        return nil
    }
    return value
}

By having let inside:

var asInt: Int? {
    guard case .asInt(let value) = self else {
        return nil
    }
    return value
}

The last one is my personal favorite syntax of the four solutions.

Leave a Comment