Goto default case in switch

Hi,

Let's consider this hypothetical flow where I have a switch statement and I'd like to jump to default case whenever a condition is met:

switch value {
case foo:
    if condition {
         break default // invalid syntax
    }
case bar: 
    print("bar")
default:
    handle()

this could use case foo where condition::

switch value {
case foo where condition:
     handleFoo()
case bar: 
    print("bar")
default:
    handle()

it's getting a bit annoying with multiple case for single block though:

switch value {
case foo where condition,
     zoo where condition:
     handleFooZoo()
case bar: 
    print("bar")
default:
    handle()

it's getting even more verbose in case it's just about checking optional value

switch value {
case foo where variable != nil,
     zoo where variable != nil:
     guard let variable = variable else { break }
     handleFooZoo(variable)
case bar: 
    print("bar")
default:
    handle()

so, at this point I'd like to break label (aka goto), where label is a default case - this can't be done as of today, can it?

2 Likes

You can improve this by making the optional part of the switched expression:

switch (value, variable) {
case (foo, variable?), (zoo, variable?):
	handleFooZoo(variable)
case (foo, _):
	break
case (bar, _): 
	print("bar")
default:
	handle()
}
1 Like

it doesn't scale well

Maybe you could do

switch value {
case bar: 
    print("bar")
case foo where condition:
    fallthrough
default:
    handle()
}

this only works by accident and is rather error-prone. I wouldn't go this way ;) Easy to miss when change