SwiftFormat icon indicating copy to clipboard operation
SwiftFormat copied to clipboard

Indent nested ternary expressions

Open karlpuusepp opened this issue 6 years ago • 4 comments

When using nested ternary expressions it would be nice if the inner expressions were indented. Xcode's native indentation already seems to support this, but SwiftFormat flattens the ternary making it hard to read.

Ideal

return firstCondition
    ? secondCondition
        ? "X"
        : "Y"
    : "Z"

Current

return firstCondition
    ? secondCondition
    ? "X"
    : "Y"
    : "Z"

karlpuusepp avatar Sep 26 '19 14:09 karlpuusepp

Side note: I would recommend not using nested ternary operators. Choose readability over brevity.

lordzsolt avatar Oct 19 '19 23:10 lordzsolt

I think my PR #528 might fix this. If it doesn't, we should look at this. With the code I've added there, it shouldn't be hard to fix this next.

AnthonyMDev avatar Jan 09 '20 05:01 AnthonyMDev

It's not only about nested ternary expressions but about all nested multiline expressions

The generalization sounds as: each nested multiline expression should be indented as if it was written in top-level

For example, the following code should be preserved:

1 == 2
    ? "foo"
        .prefix(2)
        .contains("bar")
    : false

Right now, swiftformat formats it to:

1 == 2
    ? "foo"
    .prefix(2)
    .contains("bar")
    : false

nikitabobko avatar Sep 06 '24 22:09 nikitabobko

Just discovered by browsing the source code that swiftformat --wrapternary before-operators fixes the problem for ternary operators.

But the problem is still there for other multiline expressions:

"foo" +
    "bar"
        .substring() // swiftformat will push this line to the left

nikitabobko avatar Sep 06 '24 23:09 nikitabobko