Reputation: 485
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
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