像if語句一樣,guard的執(zhí)行取決于一個表達(dá)式的布爾值。我們可以使用guard語句來要求條件必須為真時,以執(zhí)行g(shù)uard語句后的代碼。不同于if語句,一個guard語句總是有一個else從句,如果條件不為真則執(zhí)行else從句中的代碼。
func greet(person:[String:String]){
guard let name = person["name"] else {
return
}
print("Hello \(name)")
guard let location = person["location"] else {
print("I hope the weather is nice near you")
return
}
print("I hope the weather is nice in \(location)")
}
greet(person: ["name":"John"])
print("----------------------------------------------------------------------")
greet(person: ["name":"Jane","location":"Cupertion"])
Log
Hello John
I hope the weather is nice near you
Hello Jane
I hope the weather is nice in Cupertion
如果guard語句的條件被滿足,則繼續(xù)執(zhí)行g(shù)uard語句大括號后的代碼。將變量或者常量的可選綁定作為guard語句的條件,都可以保護(hù)guard語句后面的代碼。
如果條件不被滿足,在else分支上的代碼就會被執(zhí)行。這個分支必須轉(zhuǎn)移控制以退出guard語句出現(xiàn)的代碼段。它可以用控制轉(zhuǎn)移語句如return,break,continue或者throw做這件事,或者調(diào)用一個不返回的方法或函數(shù),例如fatalError()。
相比于可以實(shí)現(xiàn)同樣功能的if語句,按需使用guard語句會提升我們代碼的可讀性。它可以使你的代碼連貫的被執(zhí)行而不需要將它包在else塊中,它可以使你在緊鄰條件判斷的地方,處理違規(guī)的情況