swiftgotocontrol-flow

Replacement for goto statement in Swift


How can I transfer control to a specific line in Swift code?

In Objective-C I would do something like the following, using goto

if(a==b)
{
    goto i123;
}
else
{
    goto i456;
}
NSLog(@"the not reachable point");
i123:
NSLog(@"line 123 is here");
int j = 5;
int x = 2+j;
i456:
NSLog(@"line 456 is here");

The only control transfer statements in Swift I could find were continue, break, fallthrough, and return

continue and break only work with loops; return and fallthrough don't transfer control this way.

What can I use?

EDIT:-

Julien__'s answer didn't actually solve my problem but it could be the only available option right now. so i have accepted the answer by Julien__


Solution

  • Perhaps a switch statement ?

    switch (a==b){
    default:
        NSLog(@"the not reachable point");
        fallthrough­
    case true:
        NSLog(@"line 123 is here");
        int j = 5;
        int x = 2+j;
        fallthrough­
    case false:
        NSLog(@"line 456 is here");
    }
    

    EDIT : Here is how you could go backward.

    let START = 0
    let STOP  = -1
    var label = START
    
    while(label != STOP){
        switch (label){
    
        default:
            label = START­
    
        case START:
            NSLog(@"the not reachable point");
            if a==b {
                label = 123
            } else {
                label = 456
            }
    
        case 123:
            NSLog(@"line 123 is here");
            int j = 5;
            int x = 2+j;
            fallthrough­
    
        case 456:
            NSLog(@"line 456 is here");
            fallthrough
    
        case STOP:
            label = STOP
        }
    }
    

    Wrap your code in a giant (but well organized) switch statement. You could even create a function named goto in order to modify the value of the label var.