And*_*rea 3 if-statement guard optional swift
我试图break在一个guard声明中使用,但编译器告诉我
'break'只允许在循环内,if,do或switch
是否有可能写出这个片段(这只是一个MCV)?
func test(string: String?, x: Int) {
print("Function Scope BEGIN")
if x > 4 {
guard let pr = string else { break }
print(pr)
}
else {
print("Not")
}
print("Function Scope END")
}
Run Code Online (Sandbox Code Playgroud)
对的,这是可能的.您可以break在循环内使用未标记的语句,但不能在if块内使用.您可以使用带标签的break语句.例如,此版本的代码将起作用:
func test(string: String?, x: Int) {
print("Function Scope BEGIN")
someLabel: if x > 4 {
guard let pr = string else { break someLabel }
print(pr)
}
else {
print("Not")
}
print("Function Scope END")
}
Run Code Online (Sandbox Code Playgroud)