xcodeswiftui

SwiftUI program with Xcode 15.4 display error : "Failed to produce diagnostic for expression"


An error "Failed to produce diagnostic for expression" occurred when running this swiftui program. But after deleting the sentence ".onDrop(of: ....", the program can run normally. How to fix this program?

The source program is as follows :

import SwiftUI
struct ContentView: View {
    var body: some View {
        VStack {
            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()
    }
}

Failed to produce diagnostic for expression


Solution

  • I found the issue is your line:

    .onDrop(of: [NSPasteboard.PasteboardType.string], delegate: DropViewDelegate2())
    

    If you read the documentation, the of parameter is meant to be [UTType] which is basically a unique ID of some type of data format (like .png, .jpg, .xml etc.), and NSPasteboard.PasteboardType.string is not a UTType.

    To allow the user to drop text on the button, (which I'd firstly make bigger to make it easier, with the controlSize(.extraLarge) modifier) you can set the of parameter of .onDrop to UTType.plainText:

            VStack {
                Button(action: {}) {
                    Text("Sign In")
                }
                .onDrop(of: [.plainText], delegate: DropViewDelegate2())
            }
    

    (The rest of the code is fine and does not need to be changed.)