運命のピラミッド
If
ステートメントが過度にネストされたコードのこと。
運命のピラミッド
func singBirthdaySong() {
if isBirthday {
if guests > 0 {
if haveCakes {
print("Happy birthday to you!")
} else {
print("We need the cakes!!!")
}
} else {
print("It's just my family.")
}
} else {
print("It's not anyone's birthday...")
}
}
コードを目で追っても、本当に実行したいコードになかなか辿り着かない...。
Guard構文のキホン
If
構文とは制御フローが逆な感じなので、注意。
guard構文
guard condition else {
// condition == false の場合に実行したいコード
// 関数内なら return で脱出できる
}
// condition == true の場合に実行したいコード
運命のピラミッドをリファクタリング
いわゆる 早期リターン な記述になるので、コードが読みやすくなる。
guard構文
func singBirthdaySong() {
guard isBirthday else {
print("It's not anyone's birthday...")
return
}
guard guests > 0 else {
print("It's just my family.")
return
}
guard haveCakes else {
print("We need the cakes!!!")
return
}
print("Happy birthday to you!")
}
Guard
構文によって、本当に実行したいコードが関数定義内の最下部に移動した。