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

为视图添加EnvironmentObject导致navigationDestination报错

解决方法

方法1:使用闭包创建PlaceView

直接修改navigationDestination的闭包实现,手动传入placeID并创建PlaceView,环境对象会自动从当前视图环境中注入:

.navigationDestination(for: String.self) { placeId in
    PlaceView(googlePlaceId: placeId)
}

方法2:自定义PlaceView的初始化器

给PlaceView添加一个仅接收googlePlaceId的初始化器,覆盖自动生成的包含环境对象的初始化器:

struct PlaceView: View {
    let googlePlaceId: String
    @EnvironmentObject var startupViewModel: StartupViewModel
    
    // 自定义初始化器
    init(googlePlaceId: String) {
        self.googlePlaceId = googlePlaceId
    }
    
    var body: some View {
        // 视图内容
    }
}

之后就可以继续使用navigationDestination(for: String.self, destination: PlaceView.init)的写法。


问题原因

当PlaceView添加@EnvironmentObject后,Swift自动生成的成员初始化器会将环境对象也纳入参数列表,导致PlaceView.init的类型变为(String, StartupViewModel) -> PlaceView,但navigationDestination期望的是(String) -> PlaceView类型的闭包,因此出现类型不匹配的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:32:08