如果Swift’guard’语句必须退出范围,范围的定义是什么?
我对代码块或“范围”的定义感到困惑.苹果公司的卫士文件说:保护声明的其他部分……
其他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子句中. 我完全误解了“范围”的含义吗?范围是指方法中包含的代码吗?如果是这样,if语句中存在的’space’的正确术语是什么?
完全有可能做你想象的事情,它恰好不是那个特定的代码所做的. return始终退出方法,而不是本地范围.要做你想做的事,你可以使用标签,并打破:
func testGuardControlFlow () { let x = 2 let y = 2 func embededFunc () { breakLabel: if y == 2 { guard x == 1 else { print("oops,number is not 1") break breakLabel } 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() 要添加到vadian’s answer: 警卫强制您使用控制转移声明退出范围.有4个可供选择: > return并抛出两个退出函数/方法 此外,您可以通过调用返回 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |