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

Xcode15中SwiftUI Map视图ForEach+Marker编译报错求助

Xcode 15 SwiftUI 编译错误:"Failed to produce diagnostic for expression" 解决方法

你的编译错误是因为Marker组件和ForEach循环的放置位置错误,SwiftUI的Map视图要求所有标注(比如Marker)必须嵌套在它的内容闭包中,而不是作为同级视图放在VStack里。这种结构问题让Swift编译器无法正确解析语法,从而抛出这个模糊的错误提示。

修复步骤:

把生成Marker的ForEach循环移动到Map视图的内部,作为Map的内容参数传递。修改后的关键代码如下:

var body: some View {
    NavigationView {
        VStack {
            // 修改Map部分,将ForEach放入Map的content闭包
            Map(coordinateRegion: $region, showsUserLocation: true, userTrackingMode: .constant(.follow)) {
                ForEach(results, id: \.self) { item in
                    let placemark = item.placemark
                    Marker(placemark.name ?? "", coordinate: placemark.coordinate)
                }
            }
            .edgesIgnoringSafeArea(.all)
            .onAppear {
                locationManager.requestWhenInUseAuthorization()
            }
        }
        // 以下原有代码保持不变
        .overlay(alignment: .bottom) {
            TextField("Suche beispielsweise nach \"Kebab\"", text: $searchText)
                .cornerRadius(12)
                .font(.subheadline)
                .padding(12)
                .background(.thinMaterial)
                .padding()
                .shadow(radius: 10)
        }
        .onSubmit(of: .text) {
            Task { await searchPlaces() }
        }
        .onChange(of: mapSelection, { oldValue, newValue in
            showDetails = newValue != nil
        })
        .sheet(isPresented: $showDetails, content: {
            LocationDeatilsView(mapSelection: $mapSelection, show: $showDetails, getDirections: $getDirections)
                .presentationDetents([.height(340)])
                .presentationBackgroundInteraction(.enabled(upThrough: .height(340)))
                .presentationCornerRadius(12)
        })
        .mapControls {
            MapCompass()
            MapPitchToggle()
            MapUserLocationButton()
        }
        .onAppear() {
            Task { await searchKebab() }
        }
        .navigationBarTitle("Ort des Dönermannes", displayMode: .inline)
    }
}

额外说明:

  • 如果你使用的是iOS 16及以上版本,建议将NavigationView替换为NavigationStack,避免API过时警告。
  • 编译器抛出"Failed to produce diagnostic"这类错误时,通常是语法结构不符合组件要求,优先检查视图嵌套关系是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:25:00