iosswiftxcodeswiftui

Swift Cannot convert value of type '()' to expected argument type '() -> Void'


I am pretty new to Swift and have come across a puzzling error.

I have a Menu inside an view:

Menu("Report an issue") {
    Button("Pothole", action: passReport(rtype: "Pothole"))
    Button("Street Obstruction", action: passReport(rtype: "Street Obstruction"))
    Button("Weather Damage", action: passReport(rtype: "Weather Damage"))
    Button("Vehicular Accident", action: passReport(rtype: "Vehicular Accident"))
    Button("Other Issue", action: passReport(rtype: "Other Issue"))
}

Then, defined within this view is a function named passReport, it looks like so:

func passReport(rtype: String) {
    let lat1:String = "\(LocationHelper.currentLocation.latitude)"
    let long1:String = "\(LocationHelper.currentLocation.longitude)"

    dataManager.addReport(id: "ID goes here", latitude: lat1, longitude: long1, reportType: rtype)        
}

I am getting the error:

Cannot convert value of type '()' to expected argument type '() -> Void'

on all five lines in my Menu, up until recently, this function had no parameters and worked just fine, I recently added the reportType field to my dataManager and added a parameter to the function, and now it doesn't work. I am sure this is something simple, I checked the other questions but they didn't answer my question. Thanks


Solution

  • You need to pass a closure to the button action. And not void like you do now.

    You can try

    Button("Street Obstruction", action: { passReport(rtype: "Street Obstruction") })