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

后端 未结 3 950
南笙
南笙 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:20

    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
    }
    

提交回复
热议问题