简体   繁体   English

在swift枚举中访问值

[英]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: 您可以在没有这样的switch情况下制作:

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 : 这不是最漂亮的方式,但在游乐场玩耍我能够使用switchcase提取该值:

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: 更漂亮的方法是为枚举编写一个返回可选T和U类型元组的方法:

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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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