Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why switch does not accept case nil in optional?

I was working with optional in switch which I noticed switch cannot accept nil as a case!

func test(value: Bool?) {
    switch value {
    case true: print("true")
    case false: print("false")
    case nil: print("nil")
    }
}

Error: Switch must be exhaustive

then I used default for solving the issue, but I am looking to learn why nil cannot work in first code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think this is just an incorrect diagnostic. You can add a default case, and this code will work, but I’m actually surprised that works.

You see, the value you’re switching on is a Bool?, but 2 of the values you’re comparing it against are true and false. The typical approach for this is to use pattern matching:

func test(value: Bool?) {
    switch value {
    case .some(true): print("true")
    case .some(false): print("false")
    case .none: print("nil")
    }
}

This works correctly, but it’s a bit wordy. Luckily, Swift has a syntactic sugar for pattern matching against optionals, ? and nil:

func test(value: Bool?) {
    switch value {
    case true?: print("true")
    case false?: print("false")
    case nil: print("nil")
    }
}

Both of these snippets compile and work fine. It does open a new question as to why your original cases worked, if only you added the default.

I suggest you post about this on Swift forums, to get more input from the compiler nerds 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading