diff --git a/README.md b/README.md index 2e89b32..9be75d0 100644 --- a/README.md +++ b/README.md @@ -1476,6 +1476,56 @@ _You can enable the following settings in Xcode by running [this script](https:/ +- (link) **Prefer `if` expressions over ternary operators for single-expression return values.** Use ternary operators for conditions nested in other expressions, such as SwiftUI modifier conditions. Generally prefer `if` expressions for assignments after `=` operators. + +
+ + + + [![SwiftFormat: ifExpressions](https://img.shields.io/badge/SwiftFormat-ifExpressions-7B0051.svg)](https://swiftformat.info/rules/prerelease#ifExpressions) + + #### Why? + + If expressions are more readable than ternary expressions, especially for multiple nested conditions or multi-line values. + + ```swift + // WRONG + var destination: Planet { + spaceship.hasWarpDrive + ? .proximaCentauri + : .mars + } + + // RIGHT + var destination: Planet { + if spaceship.hasWarpDrive { + .proximaCentauri + } else { + .mars + } + } + + // ALSO RIGHT. Single-line ternaries are permitted. + var color: Color { + spaceship.velocity > 0 ? .orange : .blue + } + + // ALSO RIGHT. Use ternaries for conditions nested in other expressions, + // like SwiftUI modifier conditions. + Image(.spaceship) + .foregroundStyle(spaceship.velocity > 0 ? .orange : .blue) + + // PREFERRED. `if` expressions are also generally preferred over ternaries for assignments. + let destination: Planet = + if spaceship.hasWarpDrive { + .proximaCentauri + } else { + .mars + } + ``` + +
+ - (link) **Wrap `if` statement and `if` expression bodies onto multiple lines.**
diff --git a/Sources/AirbnbSwiftFormatTool/airbnb.swiftformat b/Sources/AirbnbSwiftFormatTool/airbnb.swiftformat index 41998e0..2174c2a 100644 --- a/Sources/AirbnbSwiftFormatTool/airbnb.swiftformat +++ b/Sources/AirbnbSwiftFormatTool/airbnb.swiftformat @@ -46,6 +46,7 @@ --else-position same-line # elseOnSameLine --guard-else next-line # elseOnSameLine --single-line-for-each convert # preferForLoop +--single-line-ternary preserve # ifExpressions --short-optionals always # typeSugar --semicolons never # semicolons --doc-comments preserve # docComments @@ -125,6 +126,7 @@ --rules sortTypealiases --rules preferForLoop --rules conditionalAssignment +--rules ifExpressions --rules wrapMultilineConditionalAssignment --rules wrapFunctionBodies --rules wrapPropertyBodies