Early exit from Select

I did wonder whether if I have:

Select Case myvar

Case 27
if  (othervar=15)  then exit

...

that this would be the way to cause an early exit from a particular Case with execution continuing after the End Select. However it does not. I could of course just invert the sense of the If and put the code for the Case inside it but I view all such strictures as clumsy. Am I overlooking a way to exit early from a Case?

exit will leave a loop or method early (see http://docs.xojo.com/Exit)
there is no such syntax for a select case statement

of course you could always write a select case as

Select Case true

Case (myvar = 27) and (othervar <>15)  
     // code you want to perform when other var <> 15
1 Like

Hmm yesss. That’s very nearly an if-then-elseif …

But it suits in this instance, thanks.

You could wrap the select statement in a do-loop. The Exit would then leave the loop instead of the method.

do
  Select Case myvar
  Case 27
    if (othervar = 15) then Exit do
    ...
  End Select
loop until true

Because the loop’s condition is true, it will only run once. This solution also is quite ugly, but just to give you an alternative…

Just remember that the scope of any variables you declare within the do-loop is local to that loop.

select case is basically syntactic sugar instead of if then else in nearly every language :stuck_out_tongue:

I see that Swift uses Break for an early exit of a Select, and has Fallthrough to allow execution to drop into the following case (as is the default for JS and PHP). Pity Xojo doesn’t have those.

I’m glad they dont as that is very “C” like
Break is the traditional C mechanism for ending the code in a specific case
Fallthrough was what you got IF you forgot to put in a break

1 Like

I hate fall through languages. It’s waaay too easy for subtle bugs to creep in.

2 Likes

you get into the habit of writing the BREAK statement FIRST then filling in code before it :stuck_out_tongue:

1 Like

I’m not talking about fall through languages. I’m glad that Xojo isn’t one. I’m just pointing out that Swift has a FallThrough statement which implements what happens by default in languages like C, PHP, Javascript. I think that would be a useful addition to Xojo, as would adjusting Exit so that it works inside a Select Case to exit the Select Case, not to exit any enclosing loop or method.

Hope that’s clear now.

I would respectfully disagree about Fallthrough and would prefer they do not add it
Exit might be useful
They’d need a compiler person to implement them