xcode Swift 在枚举上使用 if 导致错误无法转换为“_ArrayCastKind”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24668210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift using if on an enum resulting in error not convertible to '_ArrayCastKind'
提问by Tod Cunningham
I'm using Beta 3 of xcode 6, and I am having a problem doing a simple if statement against an enum passed into an argument of a closure. Here is the simple enum definition:
我正在使用 xcode 6 的 Beta 3,并且我在针对传递给闭包参数的枚举执行简单的 if 语句时遇到问题。这是简单的枚举定义:
enum FLSTeslaLoginStatus {
case LoggedOut
case LoggedIn
case LoggingIn
case LoginFailed(NSData!, NSHTTPURLResponse!, NSError)
}
And the code with the error is:
有错误的代码是:
As you can see the switch statement works fine, but the if check is resulting in the error. This is just some test code so I won't normally have a switch and an if statement, but I'm trying to figure out what's wrong with the if statement. I'm thinking it is a compiler bug.
如您所见,switch 语句工作正常,但 if 检查导致错误。这只是一些测试代码,所以我通常不会有 switch 和 if 语句,但我试图找出 if 语句有什么问题。我认为这是一个编译器错误。
This is supported in Swift 2.0 with the use of "if case".
Swift 2.0 支持使用“if case”。
回答by Tod Cunningham
Swift 2.x allows this via the if case pattern match: https://www.natashatherobot.com/swift-2-pattern-matching-with-if-case/
Swift 2.x 通过 if case 模式匹配允许这样做:https: //www.natashatherobot.com/swift-2-pattern-matching-with-if-case/
if case let .LoggedIn(name,password) = status {
print( "\(name) Logged in!" )
}
回答by Michael Peterson
At this time (iOS8 Beta 4) it seems you need to fully-quality the enum value when doing an == comparison.
此时(iOS8 Beta 4)似乎您需要在进行 == 比较时完全确定枚举值的质量。
OK:
好的:
if (taskSortOrder == TaskSortOrder.Name) {
...
}
Error:"TaskSortOrder' is not convertible to 'Selector'"
错误:“TaskSortOrder”不能转换为“Selector”
if (taskSortOrder == .Name) {
...
}
回答by cybercow
It happens in my enum example also, but i'm using Int type
它也发生在我的枚举示例中,但我使用的是 Int 类型
enum DisplayFunctionKey : Int {
case Auto, A, B, C, D, E, F, G, H
}
var key : DisplayFunctionKey = .Auto;
if key == .Auto { /* do your stuff */ } // gives error
But! ... strangely enough with using not operator in if statement with accompanying else it works:
但!... 奇怪的是,在 if 语句中使用 not 运算符并伴随 else 它可以工作:
if key != .Auto {} else { /* do your stuff */ } // this works
It's kinda ugly, but rather one else more, than the whole switch real estate for just one line check.
这有点丑陋,但比仅进行一次线路检查的整个交换机房地产还要多。
回答by Sherwin Zadeh
You're supposed to use the switch statement with enums.
您应该将 switch 语句与枚举一起使用。
switch task order {
case .Name:
...
default:
break
}