LoginSignup
0
3

More than 3 years have passed since last update.

SwiftプログラミングにおけるGuard構文

Last updated at Posted at 2019-05-22

運命のピラミッド

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 構文によって、本当に実行したいコードが関数定義内の最下部に移動した。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3