Swift: Those switch default statements

In Swift, all switch statements must be complete. You cannot just test for the cases you’re interested in. Maurice Sharp was kind enough to track down how to perform the Swift equivalent of default: break for me after I complained about the error produced by the following example.  This snippet raises a “Switch must be exhaustive, consider adding a default clause” complaint.

switch (name) {
case "Erica" : println("Hello Erica")

But say you don’t want to do anything as the alternative. How do you create a nothing default clase?  Well, you don’t have to write a “doNothing” func or try to use “;” or “{}”. Just pass a set of parentheses as follows:

switch (name) {
case "Erica" : println("Hello Erica")
default: ()

Thanks, Maurice!


  • The language guide suggests “break”: “Because Swift’s switch statement is exhaustive and does not allow empty cases, it is sometimes necessary to deliberately match and ignore a case in order to make your intentions explicit. You do this by writing the break statement as the entire body of the case you want to ignore.” (I haven’t tried this yet, I’m at lunch.)

    Excerpt From: “The Swift Programming Language.” Apple Inc., 2014-05-27T07:00:00Z.

    • Please let me know one way or another!

    • I was going to comment this, although i figured someone would have already did.

      Given that Swift does not automatically fall-through each case statement by default, this is probably one of the few situations you would use a break statement inside a case.

  • It works; the following code in a playground:

    func yTown(name: String) {
    switch (name) {
    case “SF”:
    println(“Try Lulu’s”)
    case “Nowheresville”:

  • Thanks again for testing that!

  • […] Notice that empty brackets: (). More here. […]