Why is forced deployment required when renaming and switching?

I noticed a strange fast behavior, because, in my opinion, the color variable should not be deployed in the case of the switch written below, but without deploying the compiler an error message is displayed.

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 the color variable does not expand, the compiler shows me that the error is: enter image description here

In my opinion, this is a quick inconsistency, does anyone have any ideas?

+30
enums ios swift
Nov 12 '15 at 12:03
source share
3 answers

When used in a switch , even implicitly expanded options do not expand automatically. (The reason may be that you could not match them with nil otherwise.)

So you need to expand (either forcefully with colours! Which will work if colours == nil or with optional binding), or - alternatively - match .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 applies to other expressions for pattern matching, for example

 if case .Red? = colours { // colours is .Red } else { // colours is .White, .Black or nil } 

It also has nothing to do with enumeration types, only with implicitly expanded options in the template:

 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 } 
+31
Nov 12 '15 at 12:16
source share

This is because you are creating the colours variable as an optional type. If you do like this:

 var colours: Colours colours = .Red 

you do not have to disclose this value

If we look at what an optional type is, we will see that this enum is like:

 enum Optional<T> { case Some(T) case None } 

And it can be Some Int type, for example, or None , in which case it is nil.

When you do this:

 var colours: Colours! 

directly indicates to you ! that it is not a type of colours , but it is an enum ImplicitlyUnwrappedOptional<Colours> type enum ImplicitlyUnwrappedOptional<Colours> . At the time of creation there will be Some<Colours> if it is equal, but with this ! you have it enum ImplicitlyUnwrappedOptional<Colours> , and the next moment it will be None . That is why you should use ! in switch :

Your colours value is of type ImplicitlyUnwrappedOptional<Colours> and can be colours or nil , and you need to directly indicate that it is colours enter `switch``.

+2
Nov 12 '15 at 12:08
source share

Instead of using:

 var colours: Colours! colours = .Red 

Just use

 var colours = Colours.Red 

That should do the trick.

+1
Nov 12 '15 at 12:14
source share



All Articles