无法访问Swift枚举值

Ost*_*huk 4 enums objective-c ios swift

我在下面的类中定义了枚举:

public class MyError: NSError {

    public enum Type: Int {
        case ConnectionError
        case ServerError
    }

    init(type: Type) {
        super.init(domain: "domain", code: type.rawValue, userInfo: [:])
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的测试中稍后检查错误时:

expect(error.code).to(equal(MyError.Type.ConnectionError.rawValue))
Run Code Online (Sandbox Code Playgroud)

我收到编译错误: Type MyError.Type has no member ConnectionError

我在这里做错了什么想法?

aya*_*aio 6

问题是,这Type是一个Swift关键字,您的自定义会Type混淆编译器.

在我在Playground中的测试中,您的代码生成了相同的错误.解决方案是更改Type任何其他名称.示例Kind:

public enum Kind: Int {
    case ConnectionError
    case ServerError
}

init(type: Kind) {
    super.init(domain: "domain", code: type.rawValue, userInfo: [:])
}
Run Code Online (Sandbox Code Playgroud)

然后

MyError.Kind.ConnectionError.rawValue
Run Code Online (Sandbox Code Playgroud)

按预期工作.