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.
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?
CodePudding user response:
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)