realm / SwiftLint

A tool to enforce Swift style and conventions.
https://realm.github.io/SwiftLint
MIT License
18.64k stars 2.22k forks source link

Rule Request: `explicit_view_spacing` #4962

Open knellr opened 1 year ago

knellr commented 1 year ago

New rule request

Having migrated to SwiftUI, a major issue we encountered was not understanding (and subsequently remembering to account for) the fact that Spacer, and V/HStack variants had a non-zero default spacing. We've added a rule locally to enforce that spacing should be explicit to avoid unexpected behaviour.

Triggering examples:

Spacer()
VStack {
    Text("Hello World")
}
LazyHStack(
    alignment: .leading
) {
    Text("Hello World")
}

Non-triggering examples:

Spacer(minLength: 8)
Spacer(minLength: .zero)
VStack(spacing: 8) {
    Text("Hello World")
}
LazyHStack(
    alignment: .leading,
    spacing: .zero
) {
    Text("Hello World")
}

This should not be enabled by default as the default behaviour is desired in some applications.

SimplyDanny commented 1 year ago

Would you like to contribute the rule you already use internally?

knellr commented 1 year ago

We have two very hacked together regular expression based rules currently:

  swiftui_stack_spacing:
    included: ".*\\.swift"
    name: "SwiftUI Stack spacing"
    regex: "[^A-Z^a-z][V|H]Stack(?![^\\)]+spacing[^\\)]+)"
    capture_group: 0
    message: "VStacks and HStacks must be given explicit spacing"
    severity: error
  swiftui_spacer_length:
    included: ".*\\.swift"
    name: "SwiftUI Spacer minimum length"
    regex: "[^A-Z^a-z]Spacer(?![^\\)]+minLength[^\\)]+)"
    capture_group: 0
    message: "Spacers must be given explicit minimum length"

These don't account for lazy stacks or much else but I had forgotten they do try to ignore unrelated definitions that start SomeOtherStack()