iosswiftswift4

Swift return associated enum value or nil in one line


Case statements are not always intuitive, especially outside of switch statements.

Is it possible to return the associated value of an enum case only if that case matches, otherwise nil, in one line. Here's the code:

struct Something<B> {
    enum Base {
        case common(B)
        case extended([B])
    }

    let base:Base

    var common:B? {
        switch base {
        case .common(let common) :
            return common
        default:
            return nil
        }
    }
}

See how common has a lot of boilerplate just to return the associated value of common if it exists. I would hope for syntax similar to this (or even simpler):

var common:B? {
    return case base as .common(let common)
}

(currently using Swift 4)


Solution

  • This is a bit shorter

    var common: B? {
        if case let .common(common) = base { common } else { nil }
    }