LoginSignup
5
0

More than 3 years have passed since last update.

[Xcode 12] [Swift] guard節で複数条件を判定する時の推奨コーディングスタイル

Last updated at Posted at 2020-12-24

Xcode 12でguard節の自動フォーマットが変わりました。
Xcode 12以降でのコーディングスタイルについての考察です。

Xcode 11以前の自動フォーマットと、私個人のコーディングスタイル

func foo() {
    // Xcode 11の自動フォーマット。letの位置がズレていて読みづらい…
    guard let hoge = hoge,
        let fuga = fuga else {
            print("guarded")
            return
    }
    print("\(hoge) - \(fuga)")
}

func bar() {
    // 上だと読みづらいので、Xcode 11ではこう書いてました。
    guard
        let hoge = hoge,
        let fuga = fuga
        else {
            print("guarded")
            return
    }
    print("\(hoge) - \(fuga)")
}

Xcode 12以降の自動フォーマット

func foo() {
    // Xcode 12の自動フォーマット。letの位置が合って読みやすくなりました。多分これが推奨のスタイル。
    guard let hoge = hoge,
          let fuga = fuga else {
        print("guarded")
        return
    }
    print("\(hoge) - \(fuga)")
}

func bar() {
    // Xcode 11以前のスタイルだと、elseの位置が変わりました。
    // 別にこれでも悪くはないけど、Xcodeが上の自動フォーマットをしてくれるなら、このスタイルで書く必要性はなくなりました。
    guard
        let hoge = hoge,
        let fuga = fuga
    else {
        print("guarded")
        return
    }
    print("\(hoge) - \(fuga)")
}

Xcode 12のリリースノート(英語)では、前者 func foo() のスタイルが例示されていますので、Xcode 12以降では前者のスタイルで書くのが良さそうです。

番外:

func foo() {
    // returnするだけならこれでも良いかと思われます。
    guard let hoge = hoge else { return }
    guard let fuga = fuga else { return }
    print("\(hoge) - \(fuga)")
}
5
0
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
5
0