Swift 在 guard 语句中使用 break
Swift use of break in guard statement
我试图在 guard
语句中使用 break
,但编译器告诉我
'break' is only allowed inside a loop, if, do, or 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")
}
如果 guard-let 在循环内,break
语句只能在 guard let
内使用。
在您的用例中,我认为您应该改用 if-let
,因为替代选项 return
不是您想要的。
func test(string: String?, x: Int) {
print("Function Scope BEGIN")
if x > 4 {
if let pr = string { print(pr) }
}
else {
print("Not")
}
print("Function Scope END")
}
是的,这是可能的。您可以在循环内使用未标记的 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")
}
我试图在 guard
语句中使用 break
,但编译器告诉我
'break' is only allowed inside a loop, if, do, or 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")
}
如果 guard-let 在循环内,break
语句只能在 guard let
内使用。
在您的用例中,我认为您应该改用 if-let
,因为替代选项 return
不是您想要的。
func test(string: String?, x: Int) {
print("Function Scope BEGIN")
if x > 4 {
if let pr = string { print(pr) }
}
else {
print("Not")
}
print("Function Scope END")
}
是的,这是可能的。您可以在循环内使用未标记的 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")
}