简体   繁体   中英

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)

This is a bit shorter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM