Skip to content

Failed to produce diagnostic for expression in SwiftUI code #73750

@moreindirection

Description

@moreindirection

Description

While writing a SwiftUI view, I got the following compiler error:

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

I isolated the cause to the following short snippet. I eventually figured out that the problem is on line 21. Where the example code has:

ForEach(categories, id: \.categoryName) { category in

it needs to handle the case where categories is nil. Replacing this line with the following fixes it:

ForEach(categories ?? [], id: \.categoryName) { category in

Note that if I remove the surrounding Group, I get the correct error:

Value of optional type '[CatalogCategory]?' must be unwrapped to a value of type '[CatalogCategory]'

so the Group is necessary to reproduce the bug.

Reproduction

import Foundation
import SwiftUI

struct CatalogCategory: Codable, Identifiable {
  let categoryName: String
  
  var id: String { return self.categoryName }
}

struct BasicsCatalogView: View {
  @State var categories: [CatalogCategory]? = nil
  
  var body: some View {
    Group {
      if self.categories == nil {
        Text("Loading...")
      }
      else {
        List {
          ForEach(categories, id: \.categoryName) { category in
            Text(category.categoryName.capitalized)
          }
        }
      }
    }
  }
}

Expected behavior

Instead of getting this message (which is raised at the surrounding var body: some View declaration), I should have received an error on the ForEach line, telling me that I was passing an optional to a method that expects a collection.

As described above, without the surrounding Group, I get the correct error on the correct line.

Environment

swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
Target: arm64-apple-macosx14.0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    SwiftUIFlag: Involves SwiftUIbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfdiagnostics QoIBug: Diagnostics Quality of ImplementationexpressionsFeature: expressionsfailed to produce diagnosticBug → internal error: Failed to produce diagnostic for expressionresult buildersFeature: Result buildersswift 5.10type checkerArea → compiler: Semantic analysis

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions