nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.9k stars 640 forks source link

Indent nested ternary expressions #483

Open karlpuusepp opened 5 years ago

karlpuusepp commented 5 years ago

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"
lordzsolt commented 5 years ago

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

AnthonyMDev commented 4 years ago

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.

nikitabobko commented 1 month ago

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 commented 1 month ago

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