像if語句一樣碌宴,guard的執(zhí)行取決于一個(gè)表達(dá)式的布爾值页慷。我們可以使用guard語句來要求條件必須為真時(shí)捏鱼,以執(zhí)行g(shù)uard語句后的代碼执庐。不同于if語句,一個(gè)guard語句總是有一個(gè)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語句大括號(hào)后的代碼看尼。將變量或者常量的可選綁定作為guard語句的條件递鹉,都可以保護(hù)guard語句后面的代碼。
如果條件不被滿足藏斩,在else分支上的代碼就會(huì)被執(zhí)行躏结。這個(gè)分支必須轉(zhuǎn)移控制以退出guard語句出現(xiàn)的代碼段。它可以用控制轉(zhuǎn)移語句如return,break,continue或者throw做這件事狰域,或者調(diào)用一個(gè)不返回的方法或函數(shù)媳拴,例如fatalError()。
相比于可以實(shí)現(xiàn)同樣功能的if語句兆览,按需使用guard語句會(huì)提升我們代碼的可讀性屈溉。它可以使你的代碼連貫的被執(zhí)行而不需要將它包在else塊中,它可以使你在緊鄰條件判斷的地方抬探,處理違規(guī)的情況