a switch bug in swift? - “Switch must be exhaustive, consider adding a default clause.”

前端 未结 3 777
青春惊慌失措
青春惊慌失措 2020-12-21 04:11

I am positive that the following swift code has covered all possibilities, but Xcode keeps telling me that, \"Switch must be exhaustive, consider ad

相关标签:
3条回答
  • 2020-12-21 04:49

    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.

    0 讨论(0)
  • 2020-12-21 05:02

    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

    0 讨论(0)
  • 2020-12-21 05:10

    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.

    0 讨论(0)
提交回复
热议问题