[Xcode 12] [Swift] Recommended coding style when judging multiple conditions in the guard clause

The automatic format of the guard clause has changed in Xcode 12. A discussion of coding styles in Xcode 12 and above.

Automatic formatting before Xcode 11 and my personal coding style

func foo() {
    //Xcode 11 automatic format. The position of let is misaligned and difficult to read ...
    guard let hoge = hoge,
        let fuga = fuga else {
            print("guarded")
            return
    }
    print("\(hoge) - \(fuga)")
}

func bar() {
    //It's hard to read above, so I wrote this in Xcode 11.
    guard
        let hoge = hoge,
        let fuga = fuga
        else {
            print("guarded")
            return
    }
    print("\(hoge) - \(fuga)")
}

Automatic format after Xcode 12

func foo() {
    //Xcode 12 automatic format. The position of let is aligned and it is easier to read. Maybe this is the recommended style.
    guard let hoge = hoge,
          let fuga = fuga else {
        print("guarded")
        return
    }
    print("\(hoge) - \(fuga)")
}

func bar() {
    //In the style before Xcode 11, the position of else has changed.
    //That's not bad, but if Xcode does the above auto-formatting, you no longer need to write in this style.
    guard
        let hoge = hoge,
        let fuga = fuga
    else {
        print("guarded")
        return
    }
    print("\(hoge) - \(fuga)")
}

The Xcode 12 Release Notes exemplifies the former style of func foo (), so it seems better to write in the former style in Xcode 12 and later.

Extra:

func foo() {
    //If you just want to return, this is fine.
    guard let hoge = hoge else { return }
    guard let fuga = fuga else { return }
    print("\(hoge) - \(fuga)")
}

Recommended Posts

[Xcode 12] [Swift] Recommended coding style when judging multiple conditions in the guard clause
Specify multiple sort conditions in Swift