Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix Swift warning in iOS "Multiple Closures with Trailing Closure Violation"

I am fairly new to Swift development and I’m getting the following warning:

Multiple Closures with Trailing Closure Violation: Trailing closure
syntax should not be used when passing more than one closure argument
(multiple_closures_with_trailing_closure).

I don’t really understand what the warnings means and how to fix it. I already googled and looked into other posts on Stackoverflow but couldn’t wrap my head around it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code looks like this:

Button(action: {
  address = "123 Fakestreet"
  onSubmit()
}) {
  Text("Start search")
}

Question: How can I refactor my code so the functionality stays the same but the warning goes away?

>Solution :

You simply need to use labels for both arguments and not use this short version where the last closure omits the label:

Button(action: {
    address = "123 Fakestreet"
    onSubmit()
}, label: {
    Text("Start search")
})

When things get more complicated I actually suggest you to refactor everything into methods. Then you can use it this way:

private func onAddressButtonPressed() {
    address = "123 Fakestreet"
    onSubmit()
}

Button(action: onAddressButtonPressed) {
    Text("Start search")
}

Note that there are no brackets after the method onAddressButtonPressed (not onAddressButtonPressed()).

You can do the same with label part when appropriate

private func onAddressButtonPressed() {
    address = "123 Fakestreet"
    onSubmit()
}

private func addressButtonContent() -> some View {
    Text("Start search")
}

Button(action: onAddressButtonPressed, label: addressButtonContent)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading