4

I am positive that the following swift code has covered all possibilities, but Xcode keeps telling me that, "Switch must be exhaustive, consider adding a default clause."

Can anyone tell me what did I miss? Thanks.

let a = false let b = false let c = false func test(a: Bool, _ b: Bool, _ c: Bool) { switch (a, b, c) { case (true, false, _): print("Moved left!!!") case (true, true, _): print("Moved right!!!") case (false, _, false): print("Moved up!!!") case (false, _, true): print("Moved down!!!") // Error: Switch must be exhaustive, consider adding a default clause. } } test(false, false, false) test(false, false, true) test(false, true, false) test(false, true, true) test(true, false, false) test(true, false, true) test(true, true, false) test(true, true, true) 
0

3 Answers 3

2

The compiler is unable to conclude about your pattern because it is too complex or too unusual for it. If your pattern would have been more regular like:

case (true, false, _): print("Moved left!!!") case (true, true, _): print("Moved right!!!") case (false, false, _): print("Moved up!!!") case (false, true, _): print("Moved down!!!") 

then the compiler would have not complained. It that case it is easy for it to conclude that you covered all the cases.

Sign up to request clarification or add additional context in comments.

Comments

1

In Swift, a switch statement must always provide an option for all possible cases. If you have an enum, you can add all enum values and the switch will be exhaustive. If it is not exhaustive, you need to add a default case, this will trigger when no other case is matched.

If you are switching on a variable, you should exhaust all cases. If you do that, a default case is not needed.

A programmer might be able to see that this switch is exhaustive, but the compiler does not. That is why you get the error, and you can fix it by adding a default case.

Comments

0

If you calculate all the possible combinations between three elements with two possible values, the cases are more than four. If you don't care about the others, put a default case in your switch

1 Comment

The _ (the wildcard pattern) covers the “missing cases”. Each of the cases in the question covers two possibilities — the _ can be any value, so either true or false here — for a total of all 8 (2³) possibilities covered.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.