Swiftlint: trailing_closure when the function has multiple optional closure parameters

Created on 27 Feb 2019  路  2Comments  路  Source: realm/SwiftLint

New Issue Checklist

Describe the bug

See the following function signature from RXSwift:

public func subscribe(onNext: ((Self.E) -> Void)? = default, onError: ((Error) -> Void)? = default, onCompleted: (() -> Void)? = default, onDisposed: (() -> Void)? = default) -> Disposable

A common scenario when using RXSwift is to call it like this:

observable
    .subscribe(onNext: { [weak self] in print($0) })
    .disposed(by: self.disposeBag)

Of course, the trailing_closure rule shows a warning.

Environment

  • SwiftLint version (run swiftlint version to be sure)? 0.30.1
  • Installation method used (Homebrew, CocoaPods, building from source, etc)? Homebrew
  • Are you using nested configurations?
    If so, paste their relative paths and respective contents.
    No.

  • Which Xcode version are you using (check xcode-select -p)?
    Version 10.1 (10B61)

  • Do you have a sample that shows the issue? Run echo "your_code" | swiftlint lint --no-cache --use-stdin --enable-all-rules
    to quickly test if your example is really demonstrating the issue. If your example is more
    complex, you can use swiftlint lint --path [file here] --no-cache --enable-all-rules.

echo "observable.subscribe(onNext: { [weak self] in print($0) })" | swiftlint lint --no-cache --use-stdin --enable-all-rules
<nopath>:1:1: warning: Trailing Closure Violation: Trailing closure syntax should be used whenever possible. (trailing_closure)
<nopath>:1:38: warning: Explicit Type Interface Violation: Properties should have a type interface (explicit_type_interface)
<nopath>:1:38: warning: Explicit Type Interface Violation: Properties should have a type interface (explicit_type_interface)
Done linting! Found 3 violations, 0 serious in 1 file.

I do not see how to fix this with the actual regex implementation of the trailing_closure rule

Most helpful comment

Okey, I just saw that the rule has an option to alleviate this problem, introduced in https://github.com/realm/SwiftLint/pull/2568:

# In your yml config file
trailing_closure:
  only_single_muted_parameter: true

That solved my problem. Thanks!

All 2 comments

Okey, I just saw that the rule has an option to alleviate this problem, introduced in https://github.com/realm/SwiftLint/pull/2568:

# In your yml config file
trailing_closure:
  only_single_muted_parameter: true

That solved my problem. Thanks!

This way removes the trailing closure warning without needing to change the rules in the config file:

observable
    .subscribe { [weak self] eventValue in
        if let value = eventValue.element {
            print(value)
        }
    }
    .disposed(by: self.disposeBag)

Since this way you get e.g. Event<String>, you have to use eventValue.element to get your String object.

Was this page helpful?
0 / 5 - 0 ratings