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

SwiftUI程序在Xcode15.4中报错“Failed to produce diagnostic for expression”如何修复?

修复SwiftUI中.onDrop引发的“Failed to produce diagnostic for expression”错误

问题场景

你提供的SwiftUI代码里,给Button添加.onDrop修饰符后,编译器抛出“Failed to produce diagnostic for expression”错误,删除该修饰符后程序可正常运行。

错误原因

Button是SwiftUI内置的交互式控件,自身已经绑定了点击等事件处理逻辑。直接给这类控件附加DropDelegate会触发内部类型系统冲突,编译器无法正确解析代码,进而抛出这个模糊的诊断错误。

修复方案

最直接的解决方式是给Button套一层容器视图(比如ZStack、HStack或Color.clear),将.onDrop修饰符应用到容器上,而非直接作用于Button本身。

修改后的完整代码:

import SwiftUI
struct ContentView: View {
    var body: some View {
        VStack {
            // 用ZStack包裹Button,将拖放逻辑绑定到容器上
            ZStack {
                Button(action: {}) {
                    Text("Sign In")
                }
            }
            .onDrop(of: [NSPasteboard.PasteboardType.string], delegate: DropViewDelegate2())
        }
    }
}

struct DropViewDelegate2 : DropDelegate {
    func performDrop(info: DropInfo) -> Bool {
        return true
    }
    
    func dropEntered(info: DropInfo) {
    }
    
    func dropExited(info: DropInfo) {
    }
    
    func dropUpdated(info: DropInfo) -> DropProposal? {
        return DropProposal(operation: .move)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

原理说明

通过容器视图承接拖放逻辑,避免了拖放事件与Button自身的交互逻辑冲突,让编译器能够正常解析代码结构,解决诊断错误的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:22:37