SwiftLint icon indicating copy to clipboard operation
SwiftLint copied to clipboard

Rule Request: `explicit_default_argument`

Open KacperCzapp opened this issue 2 years ago • 1 comments

New Issue Checklist

New rule request

I would like to propose a new rule explicit_default_argument which would trigger a violation if an argument passed to a function or initializer matches the default value provided by the function (or init).

Given the following code:

struct Foo {
    let bar: Bool
    let baz: String

    init(bar: Boo, baz: String = "") { ... }
    func doSomething(arg: Bool = true, arg2: String = "", arg3: Float = 0.0) { ... }
}

When calling:

let foo = Foo(bar: false, baz: "")
foo.doSomething(arg: true, arg2: "", arg3: 0.0)

Would trigger violations in both lines as they are called with the same values as their defaults. Calling Foo(bar: false, baz: "baz") would not trigger the rule.

This allows for cleaner, more concise code on the call site, especially if there are many default parameters.

let foo = Foo(bar: false)
foo.doSomething()

Should the rule be configurable, if so what parameters should be configurable?

If any, I suggest adding two params, for excluding initializers and excluding functions, both set to false by default.

Should the rule be opt-in or enabled by default? Why?

My suggestion is to set the rule as opt-in. It's a style enhancement, not a functional one.

KacperCzapp avatar Jan 10 '24 11:01 KacperCzapp

This requires to implement an Analyzer rule, because the rule needs to access the method/initializer declaration from the call-side to figure out the default parameter values. This is impossible on a syntax-level only.

SimplyDanny avatar Jan 10 '24 20:01 SimplyDanny