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?
答案 0 :(得分:33)
在switch
语句中使用时,甚至隐式解包
选项不自动解包。 (原因可能是你
否则无法与nil
匹配。)
所以你必须打开(要么强行打开
如果colours!
或使用可选绑定,colours == nil
会崩溃,或者 - { - 1}}匹配
这是.Red?
的快捷方式:
.Some(.Red)
其他模式匹配表达式也是如此,例如
var colours: Colours!
switch colours {
case .Red?:
break // colours is .Red
default:
break // colours is .White, .Black or nil
}
这也与枚举类型无关,只是隐式 处于模式中的未包装选项:
if case .Red? = colours {
// colours is .Red
} else {
// colours is .White, .Black or nil
}
答案 1 :(得分:2)
This is because you create colours
variable like optional type. If you do like this:
var colours: Colours
colours = .Red
you will not have to unwrappe this value
If we look at what the optional type is, we will see that this is enum like:
enum Optional<T> {
case Some(T)
case None
}
And it can be Some
Type like Int
for example or None
and in this case it's have nil value.
When you make this:
var colours: Colours!
you directly is indicated by the !
that this is not Colours
type but this is the enum ImplicitlyUnwrappedOptional<Colours>
type. At moment of creation it's will be Some<Colours>
if equal it value but with this !
you have that it is enum ImplicitlyUnwrappedOptional<Colours>
and in some next moment it will be the None
. That's why you have to use !
in switch
:
Your colours
value is ImplicitlyUnwrappedOptional<Colours>
type and it may be Colours
or nil
and you have to directly indicate that this is Colours
type in `switch``.
答案 2 :(得分:1)
Instead of using :
var colours: Colours!
colours = .Red
Simply use
var colours = Colours.Red
That should do the trick.