为什么在 enum 和 switch 的情况下需要强制展开? [英] Why force unwrapping is required in case of enum and switch?
问题描述
我注意到奇怪的快速行为,因为在我看来,在下面写的开关的情况下不应该强制解包颜色变量,但没有解包编译器会向我显示错误消息.
I have notice weird swift behaviour, because in my opinion colours variable shouldn't be force unwrapped in case of switch written below, but without unwrapping compiler shows me an error message.
enum Colours: Int {
case Red = 0, White, Black
}
var colours: Colours!
colours = .Red
switch colours! { // <-- why I have to unwrap colours? As you can see colours are declared as '!'
case .Red: break
default: break
}
如果颜色变量未解包,编译器会向我显示该错误:
if colours variable is not unwrapped compiler shows me that error:
在我看来这是快速的不一致,有没有人有一些想法?
in my opinion it is swift inconsistency, does anyone have some ideas?
推荐答案
更新:此问题已在 Swift 5.1 中修复. 从 CHANGELOG:
Enum case 现在可以匹配一个可选的 enum 而不需要一个 '?'在模式的末尾.
Enum cases can now be matched against an optional enum without requiring a '?' at the end of the pattern.
这也适用于您的隐式解包选项的情况:
This applies to your case of implicitly unwrapped optionals as well:
var colours: Colours!
switch colours {
case .red:
break // colours is .red
default:
break // colours is .white, .black or nil
}
上一个答案:
在 switch
语句中使用时,甚至隐式解包选项不会自动解包.(一个原因可能是你否则无法将它们与 nil
匹配.)
When used in a switch
statement, even implicitly unwrapped
optionals are not automatically unwrapped. (A reason might be that you
could not match them against nil
otherwise.)
所以你必须解开(要么强行用colours!
如果 colours == nil
或带有可选绑定会崩溃),或者 - 或者 - 匹配 .Red?
这是 .Some(.Red)
的快捷方式:
So you have to unwrap (either forcibly with
colours!
which will crash if colours == nil
, or with optional binding), or – alternatively – match against .Red?
which is a shortcut for .Some(.Red)
:
var colours: Colours!
switch colours {
case .Red?:
break // colours is .Red
default:
break // colours is .White, .Black or nil
}
同样适用于其他模式匹配表达式,例如
The same holds for other pattern-matching expressions, e.g.
if case .Red? = colours {
// colours is .Red
} else {
// colours is .White, .Black or nil
}
此外,这与枚举类型无关,仅与隐式模式中未包装的选项:
Also this has nothing to do with enumeration types, only with implicitly unwrapped optionals in a pattern:
let x : Int! = 1
switch x {
case nil:
break // x is nil
case 1?:
break // x is 1
default:
break // x is some other number
}
这篇关于为什么在 enum 和 switch 的情况下需要强制展开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!