Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

ios - 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: enter image description here

in my opinion it is swift inconsistency, does anyone have some ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: This has been fixed in Swift 5.1. From the CHANGELOG:

SR-7799:

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
}

Previous answer:

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.)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...