简体   繁体   中英

Accessing values in swift enums

I am having trouble figuring out the syntax for accessing the raw value of an enum. The code below should clarify what I am trying to do.

enum Result<T, U> {
    case Success(T)
    case Failure(U)
}

struct MyError: ErrorType {
    var status:  Int = 0
    var message: String = "An undefined error has occured."

    init(status: Int, message: String) {
        self.status = status
        self.message = message
    }
}

let goodResult: Result<String, MyError> = .Success("Some example data")
let badResult:  Result<String, MyError> = .Failure(MyError(status: 401, message: "Unauthorized"))

var a: String  = goodResult //<--- How do I get the string out of here?
var b: MyError = badResult  //<--- How do I get the error out of here?

You can make it without switch like this:

if case .Success(let str) = goodResult {
    a = str
}

It's not the prettiest way, but playing around in a playground I was able to extract that value using a switch and case :

switch goodResult {
    case let .Success(val):
        print(val)
    case let .Failure(err):
        print(err.message)
}

EDIT :
A prettier way would be to write a method for the enum that returns a tuple of optional T and U types:

enum Result<T, U> {
    case Success(T)
    case Failure(U)

    func value() -> (T?, U?) {
        switch self {
            case let .Success(value):
                return (value, nil)

            case let .Failure(value):
                return (nil, value)
        }
    }
}

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