guard
文は、if
文と同様に、式のブール値によってコードを実行します。guard
文の後のコードが実行されるには、guard 文の条件が true である必要があります。if
文と異なり、guard
文には常に else
節があり、条件が true でない場合に 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(["name": "John"])
// "Hello John!" と出力
// "I hope the weather is nice near you." と出力
greet(["name": "Jane", "location": "Cupertino"])
// "Hello Jane!" と出力
// "I hope the weather is nice in Cupertino." と出力
guard
文の条件を満たす場合、guard
文の閉じ括弧に続くコードの実行を継続します。条件の一部としてオプショナルバインディングで代入した変数値または定数値は、guard
文があるコードブロックの残りの部分で利用できます。
条件が満たされない場合には、else
分岐内のコードが実行されます。この分岐は、guard
文があるコードブロックを終了して制御を転送する必要があります。return
、break
、continue
、throw
のような制御転送文で実施するか、fatalError()
のようなリターンしない関数やメソッドを呼び出すことができます。
guard
文を使用することは、同じチェックを if
文で実施することと比較して、コードの可読性が向上します。実行するコードを else
ブロックで囲って記述する必要がなく、条件に反した場合の処理コードを条件のすぐ後に記述することができます。
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.