3

I want to modify .swiftlint.yml to add some custom rules for enforcing braces on next line. This works for me ...

  opening_braces:
    name: "Opening Braces not on Next Line"
    message: "Opening braces should be placed on the next line."
    include: "*.swift"
    regex: '\S[ \t]*\{'
    severity: warning

However there are some cases where I want to allow braces on the same line, e.g. something like this:

override var cornerRadius: CGFloat
{
    get { return layer.cornerRadius }
    set { layer.cornerRadius = newValue }
}

How do I change my regexp to allow for same line for one-line getters/setters?

BadmintonCat
  • 9,416
  • 14
  • 78
  • 129

1 Answers1

2

I suggest using

regex: '^(?![ \t]*[sg]et[ \t]+\{.*\}).*\S[ \t]*\{'

Or, its alternative with \h matching horizontal whitespace:

regex: '^(?!\h*[sg]et\h+\{.*\}).*\S\h*\{'

See the regex demo (or this one).

Details

  • ^ - start of string
  • (?!\h*[sg]et\h+\{.*\}) - a location in string that should not be immediately followed with
    • \h* - 0+ horizontal whitespaces
    • [sg]et - set or get
    • \h+ - 1+ horizontal whitespaces
    • \{.*\} - {, any 0+ chars, as many as possible, and }
  • .* - any 0+ chars, as many as possible
  • \S - a non-whitespace char
  • \h* - 0+ horizontal whitespaces
  • \{ - a { char.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks for the solution! This seems to work for most cases. I still get some warnings `Opening Braces not on Next Line Violation: Opening braces should be placed on the next line. (opening_brace)` and they just point to the top line of the source file. Any idea why this would happen? – BadmintonCat May 30 '19 at 09:37
  • @BadmintonCat No idea, if you can share some sample file text (via pastebin?) I could try to debug the regex, but probably there is no regex issue here, some other rule setting might be at fault. – Wiktor Stribiżew May 30 '19 at 10:54
  • You're right! I've copied the affected class into your demo snippet and it looks fine. Must be something else. – BadmintonCat May 31 '19 at 00:43