Home > Software design >  Using a closure vs a method within a view that takes in a closure
Using a closure vs a method within a view that takes in a closure

Time:11-17

I've been using SwiftLint and ran into multiple multiple_closures_with_trailing_closure errors defined here.

The biggest issue I had was my Button where I would toggle some boolean value, e.g.

Button(action: {self.startTimer.toggle()}) {
   ...trailing closure
}

When I switched out the short hand closure for a method

func toggleTimer() { self.startTimer.toggle() }

the linting error disappeared. I'm still not sure what the complaint was in terms of the "more than one closure argument" part.

Trailing closure syntax should not be used when passing more than one closure argument.

What is meant by this linting error in this particular example?

CodePudding user response:

Button expects two closures, one for "action" and one for "label". SwiftLint doesn't like you to leave off the label that sits in between the two closures. It is expecting this:

   Button(action: {self.startTimer.toggle()}, label: {
           ...trailing closure
        })

Your code is perfectly valid, it is just not formatted to the specs of SwiftLint.

  • Related