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

SwiftUI跳转ConfigProfileView时两类传参错误的解决方法

错误修复方案

错误1:初始化器不可访问

ConfigProfileView里的@Binding private var locationInfra被标记为private,导致Swift自动生成的初始化器也变成private,外部无法调用。直接移除private修饰符即可,或者结合场景调整属性类型。

错误2:类型不匹配

你传递的是普通可选值selectedLocationInfra,但目标视图要求的是Binding<LocationInfra?>。结合跳转详情的场景,其实不需要双向绑定——CoreData实体是引用类型,直接传递实体对象本身即可,修改其属性会自动同步到上下文。


修正后的完整代码

1. ConfigProfileView 修正

struct ConfigProfileView: View {
    @Environment(\.managedObjectContext) private var viewContext
    // 改为普通常量,无需双向绑定
    let locationInfra: LocationInfra

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack(alignment: .leading) {
                    // 用可选绑定避免强制解包,防止空值崩溃
                    if let locationName = locationInfra.locationName {
                        Text(locationName)
                    } else {
                        Text("无名称")
                    }
                }
            }
            .navigationTitle("配置详情")
        }
    }
}

2. SummaryView 修正

struct SummaryView: View {
    // 假设locationProfiles是FetchedResults<LocationInfra>类型
    let locationProfiles: FetchedResults<LocationInfra>

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                ForEach(locationProfiles) { locationProfile in
                    NavigationLink {
                        // 直接传递当前遍历的实体对象
                        ConfigProfileView(locationInfra: locationProfile)
                    } label: {
                        HStack {
                            // 这里放置你的行内容,比如展示地点名称
                            Text(locationProfile.locationName ?? "无名称")
                                .padding()
                        }
                    }
                }
            }
            .navigationTitle("Summary")
        }
    }
}

额外说明

  • 移除了原代码中冗余的@State selectedLocationInfra和onTapGesture,因为NavigationLink本身就负责跳转逻辑,点击label区域即可触发跳转。
  • 用可选绑定替代了强制解包locationInfra?.locationName!,避免空值引发崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:25:16