Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing values in swift enums

Tags:

enums

ios

swift

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?
like image 879
72A12F4E Avatar asked Jan 26 '26 10:01

72A12F4E


1 Answers

You can make it without switch like this:

if case .Success(let str) = goodResult {
    a = str
}
like image 141
Alexey Pichukov Avatar answered Jan 28 '26 00:01

Alexey Pichukov