Misleading error on ForEach

During refactoring of an app I made a typo which leads to a misleading error message in Xcode. I could reproduce it with a small sample code. Is it a bug which I should report?

Details:
I have an array containing two strings.Using a ForEach loop is fine:

        ForEach(appData.dataArray, id: \.self) { value in
            Text("\(value.subject)\t\(value.room)")   
        }

but with a typo in the Text line I got an error on the ForEach line:

        ForEach(appData.dataArray, id: \.self) { value in
--> Cannot convert value of type '[MyArray]' to expected argument type 'Binding'
            Text("\(value.subject)\t\(value.subject.room)")      
        }

Complete sample code from Swift Playground (macOS 26):

import SwiftUI

class MyArray : Hashable, Equatable, Identifiable, ObservableObject, Codable {
    let id = UUID()
    @Published var subject: String
    @Published var room   : String

    private enum CodingKeys : String, CodingKey {
        case subject
        case room
    }

    init(subject : String, room : String) {
        self.subject = subject
        self.room = room
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(subject, forKey: .subject)
        try container.encode(room, forKey: .room)
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        subject = try container.decode(String.self, forKey: .subject)
        room    = try container.decode(String.self, forKey: .room)
    }

    static func == (v1: MyArray, v2: MyArray) -> Bool {
        let result = v1.id == v2.id
        return result
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}

public class AppData : ObservableObject {
    @Published var dataArray : [MyArray] = []

    init() {
        dataArray.append(MyArray(subject: "Foo", room: "Bar"))
        dataArray.append(MyArray(subject: "Foo", room: "Batz"))
    }
}

struct ContentView: View {
    @EnvironmentObject var appData : AppData

    var body: some View {
        ForEach(appData.dataArray, id: \.self) { value in
            Text("\(value.subject)\t\(value.subject.room)")   // to fix the error replace value.subject.room with value.room
        }
    }
}

@main
struct MyApp: App {
    var appData = AppData()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appData)
        }
    }
}
2 Likes

Is it a bug which I should report?

“Bug” is a very loaded term (-: but I definitely recommend that you report this.

I’ve filed many reports of poor diagnostics over the years, and my experience is that the folks working on the compiler are happy to get such reports because they represent good signal from real world use cases.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

1 Like