Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project

When I using ForEach, Xcode gave the error like the title said. Here is the code:

//SuggestBooksRow
import SwiftUI

struct SuggestBooksRow: View {
    var items: [Book]
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(alignment: .top, spacing: 0) {
                ForEach(items) { book in
                    Text(book.name)
                }
            }
        }
    }
}

struct SuggestBooksRow_Previews: PreviewProvider {
    var books: [Book] = [
        Book(name: "EvanLuo42", imageName: "book1"),
        Book(name: "EvanLuo42", imageName: "book1")
    ]
    
    static var previews: some View {
        SuggestBooksRow(items: books)
    }
}

And other codes:

//SuggestBookItem
import SwiftUI

struct SuggestBooksItem: View {
    var book: Book
    
    var body: some View {
        VStack(alignment: .leading) {
            book.image
                .resizable()
                .frame(width: 155, height: 155)
                .cornerRadius(5)
            Text(book.name)
                .font(.caption)
        }
        .padding(.leading, 15)
    }
}

The model of the Books:

//Book
import Foundation
import SwiftUI

struct Book: Hashable, Codable {
    var name: String
    var imageName: String
    
    var image: Image {
        Image(imageName)
    }
}

Conform Book to Identifiable.

Perhaps with a computed id property like so:

var id: String { name }

Or you can use this form of ForEach:

ForEach(items, id: \.name) { book in
...blah blah blah
}

The point is, ForEach loops over items that are Identifiable or for which you supply an explicit id.

This is a bug, compiler should provide a diagnostic in this case. I'd recommend create a ticket on https://bugs.swift.org. If possible, before creating a ticket, you could test if it also happens using the latest main or 5.5 snapshot from Swift.org - Download Swift. But if is not possible you can just create the ticket =]

cc @xedin

Looks like this has been fixed already in 5.5, I saw a couple of similar reports, your code would report:

error: referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Book' conform to 'Identifiable'
                ForEach(items) { book in
                ^
note: where 'Data.Element' = 'Book'
extension ForEach where ID == Data.Element.ID, Content : View, Data.Element : Identifiable {
          ^
1 Like
Terms of Service

Privacy Policy

Cookie Policy