Search code examples
regexswiftlint

Swiftlint Regex - Custom rule regex not working


I'm trying to add a swiftlint rule about function indentation declaration. (Rule 1.9 of https://github.com/linkedin/swift-style-guide#1-code-formatting). Which function declaration of multiple parameters should like this:

func myFunctionWithManyParameters(parameterOne: String,
                                  parameterTwo: String,
                                  parameterThree: String)

The regex I wrote is

((func|init)[\s\?]?.*(?<!(,|\)|\{|\}))\n)

and another approach since negative lookbehind may not support

((func|init)((?!.*(,|\)|\{|\})).+))

But lint does not report any warning. Is regex incorrectly written or swiftLint incorrectly configured?


I've been test the following cases in online regex editor, passed. But no warning in swiftlint.

// Should Pass: Method with parameters
func foo(_ param1: String) {
}

// Should Pass: Method with parameters
func foo2(_ param1: String) {}

// Should Pass: Method with parameters in same line
func foo3(param1: String, param2: Int) {
}

// Should Pass: Method with parameters in multiple lines
func foo4(param1: String,
          param2: Int) {
}

// Should Pass: Method with no parameter
func foo5() {
}

// Should Pass: Protocol
protocol Foo {
    func foo6()
}

// Should Fail
func foo7(
    _ param1: String) {
    }

// Should Fail
func foo(
    param1: String,
    param2: Int) {
    }

Swiftlint configuration:

custom_rules:
  func_multiline_parameters:
    name: "Follow Xcode's recommended function declaration indentation style that spans multiple lines"
    regex: ((func|init)[\s\?]?.*(?<!(,|\)|\{|\}))\n)
    message: "1.9 We follow Xcode's recommended indentation style (i.e. your code should not change if CTRL-I is pressed). When declaring a function that spans multiple lines, prefer using that syntax to which Xcode, as of version 7.3, defaults."
    severity: warning

Solution

  • For starters SwiftLint regexes need to be double escaped Eg. ((func|init)((?!.*(,|\\)|\\{|\\})).+))

    But check first that swiftlint's vertical_parameter_alignment rule doesn't already achieve what you're after