You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift报错:无法将'()'类型转换为预期的'() -> Void'类型

问题原因

Button的action参数要求接收无参数、返回值为Void的闭包(即() -> Void类型),但你直接调用passReport(rtype: "xxx")时,会立刻执行该函数并返回()(无返回值函数默认返回Void),这与action需要的闭包类型不匹配,因此触发报错。

解决方法

方法一:用闭包包装函数调用

将每个Button的action改为闭包形式,点击按钮时才会执行passReport调用,符合参数类型要求:

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") })
}

也可以用Swift的尾随闭包简化写法:

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

方法二:修改passReport函数返回闭包

调整函数结构,让它直接返回符合要求的闭包,这样原Menu代码可保持不变:

func passReport(rtype: String) -> () -> Void {
    return {
        let lat1: String = "\(LocationHelper.currentLocation.latitude)"
        let long1: String = "\(LocationHelper.currentLocation.longitude)"
        dataManager.addReport(id: "ID goes here", latitude: lat1, longitude: long1, reportType: rtype)        
    }
}

内容的提问来源于stack exchange,提问作者CeilingSystems

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:01:25