Description
Previous ID | SR-13458 |
Radar | None |
Original Reporter | @klanchman |
Type | Improvement |
Additional Detail from JIRA
Votes | 0 |
Component/s | swift-format |
Labels | Improvement |
Assignee | None |
Priority | Medium |
md5: d43456d18f7712a96680bbb98f0e91ff
Issue Description:
I'd like to see swift-format include additional configuration for line break formatting that allows for some additional flexibility and strictness in where line breaks are inserted/removed.
Right now swift-format includes the respectsExistingLineBreaks
option, but setting it to false
doesn't do what I expect, nor what I'd like.
Suppose I had unformatted code that looked like this:
class MyClass {
var foo: String?
var bar: String? {
didSet {
print("foo set")
}
}
func doStuff() {
guard let foo = foo else {
return
}
doOtherStuff(foo)
}
}
Setting respectsExistingLineBreaks
to false
yields the following:
class MyClass {
var foo: String?
var bar: String? { didSet { print("foo set") } }
func doStuff() {
guard let foo = foo else { return }
doOtherStuff(foo)
}
}
Given the documentation's description, "only inserting line breaks where absolutely necessary and removing any others", what I expected would be more like this:
class MyClass {
var foo: String?
var bar: String? { didSet { print("foo set") } }
func doStuff() {
guard let foo = foo else { return }
doOtherStuff(foo)
}
}
However, my goal would be to have swift-format output the following:
class MyClass {
var foo: String?
var bar: String? {
didSet {
print("foo set")
}
}
func doStuff() {
guard let foo = foo else {
return
}
doOtherStuff(foo)
}
}
This is more in line with the output of other code formatters I use, such as Prettier.
Notably, in the desired output:
-
blank lines are removed following open and close braces (e.g. within the
class
declaration, and withindoStuff()
function) -
line breaks within braces for short statements are preserved (e.g. the entire
didSet
block, and thereturn
in theguard
) -
line breaks (or lack of) between consecutive declarations are preserved (e.g. no break between the two
var
declarations, but break between the lastvar
and thefunc
)
The second bullet point has some caveats, mainly that you'd probably want the line breaks to be consistent on each side of the block. For example, I would not want swift-format to keep this:
var bar: String? { didSet {
print("foo set")
}}
Setting respectsExistingLineBreaks
to true
and formatting the code above already results in what I'd expect / want in my "ideal" output:
var bar: String? {
didSet {
print("foo set")
}
}
I might go as far as to say that the rule I'd want for the second bullet point is basically "require a line break after opening curly braces and before closing curly braces".
As far as I can tell, with the options that swift-format has, currently it is not possible to enforce the desired output.