2017-10-07 64 views
-3

还记得End会停止一切的美好时光,而goto会带你回到某个地方而不回来吗?那么,“结束”本质上是我想要做的,是取消一个函数的其余部分。 即。快速取消功能的其余部分

func function() { 
     x = 5 
     //code to cancel and stop function 
     x = 0 
} 

我想这读出x = 5。我想这样做的原因是因为我有从函数内调用的众多函数。为了简单起见,有没有发生这种情况?

+8

您正在寻找的'return'声明? –

+1

请参见[Control Transfer Statements](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120)部分[控制流程](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID120)一章[Swift Programming Language](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0)book。 – rmaddy

回答

1

From Apple(搜索guard):

早期退出

的防护语句,如if语句,执行对表达式的布尔值取决于 语句。您使用 的警戒语句要求条件必须为真,以便执行 警戒语句后的代码。

这将是:

func function() { 
    x = 5 

    guard <yourConditionToContinue> else { 
    return 
    } 

    // Code to be executed if <yourConditionToContinue> is met. 
}