Ram Vadranam
Ram Vadranam

Reputation: 485

Swift 3.0-Switch statement without default statement getting error 'Switch must be exhaustive, consider adding default clause'

Following is the code used for executing Switch statement in playground. I executed few switch statements without using default. My doubt is why it is optional for some and mandatory for other statements.Thanks in advance!.

let someNumber = 3.5

switch someNumber {

case 2 , 3 , 5 , 7 , 11 , 13 :
  print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
  print("Normal numbers")

 }

Counter statement executed successfully without using default

  let yetAnotherPoint = (3,1)

  switch yetAnotherPoint {

  case let (x,y) where x == y :
   print("(\(x),\(y)) is on the line x == y")
  case let (x,y) where x == -y :
   print("(\(x),\(y)) is on the line x == -y")
  case let (x,y):
   print("(\(x),\(y)) is just some arbitrary point")

   }

Upvotes: 1

Views: 9865

Answers (2)

oliversisson
oliversisson

Reputation: 2309

            default:
            1 == 1

God knows why you need a default.

Upvotes: 4

Andrej
Andrej

Reputation: 7416

As other stated in comments, you should use default because in your cases you're not exposing every possible Double. But if you like more the way you did it in your second example you could do it like so:

let someNumber = 3.5
switch someNumber {
case 2 , 3 , 5 , 7 , 11 , 13 :
    print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
    print("Normal numbers")
case let x:
    print("I also have this x = \(x)")
}

Just for the reference, here's how this scenario is most often handled:

let someNumber = 3.5
switch someNumber {
case 2 , 3 , 5 , 7 , 11 , 13 :
    print("Prime numbers")
case 4 , 6 , 24 , 12 , 66 :
    print("Normal numbers")
default:
    print("I have an unexpected case.")
}

Upvotes: 11

Related Questions