Swift Guard語句
Swift Guard語句用作Swift if語句的替代方式。愛掏網 - it200.comGuard語句相比if語句提供更多好處,可以控制程序流程并編寫簡單清晰的代碼。愛掏網 - it200.com
語法
guard expression else {
//statements
//must contain a control statement:return, break, continue or throw.
}
- 在這里,expression是一個 Boolean expression(布爾表達式) ,它要么評估為true,要么評估為false。愛掏網 - it200.com
- 如果表達式評估為false,它會執行guard(保護)內的語句。愛掏網 - it200.com
- 如果表達式評估為true,它會跳過guard(保護)內的語句的執行。愛掏網 - it200.com
注意:guard(保護)語句必須在代碼末尾包含一個控制語句return、break、continue或throw。愛掏網 - it200.com
示例
guard true else {
print("Condition is not satisfied.")
}
print("Condition is satisfied.")
輸出:
Condition is satisfied.
在函數內的guard語句
示例2
在Swift中,我們也可以在函數中使用guard語句。愛掏網 - it200.com
func Function1() {
guard false else {
print("Condition is not satisfied.")
return
}
print("Condition is satisfied.")
}
Function1()
print("Hello after function call")
輸出:
Condition is not satisfied.
Hello after function call
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。