Why force unwrapping is required in case of enum and switch?

后端 未结 3 957
南笙
南笙 2020-12-03 16:51

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 sh

3条回答
  •  无人及你
    2020-12-03 17:11

    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 {
        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 type. At moment of creation it's will be Some if equal it value but with this ! you have that it is enum ImplicitlyUnwrappedOptional and in some next moment it will be the None. That's why you have to use ! in switch:

    Your colours value is ImplicitlyUnwrappedOptional type and it may be Colours or nil and you have to directly indicate that this is Colours type in `switch``.

提交回复
热议问题