我对代码块或“范围”的定义感到困惑.苹果公司的卫士文件说:保护声明的其他部分……
@H_301_20@“must transfer control to exit the code block in which the guard statement appear.”
其他online sources说守卫声明必须退出它所存在的“范围”.
所以请参考下面的示例代码:
func testGuardControlFlow () { let x = 2 let y = 2 func embededFunc () { if y == 2 { guard x == 1 else { print("oops,number is not 1") return } print ("from in embededFunc") } print ("I still want this to print even if x != 1") } embededFunc() print("Great,return still allows this to be printed.") } testGuardControlFlow()
根据我目前对’范围’的理解,代码
if y == 2 {....}
创建一个新范围,即{}之间.并且考虑到这个假设,守卫只会逃避这个范围.但事实并非如此.此实例中的Guard不会放置它所放置的函数,而不管它是否隐藏在if子句中.