SwiftUI ForEach 可绑定列表错误

SwiftUI ForEach Bindable List errors

非常感谢有关 SwiftUI 可绑定列表的帮助。 我阅读了以下文章并在我的应用程序上进行了尝试,但出现了错误。 https://www.swiftbysundell.com/articles/bindable-swiftui-list-elements/

首先,包含不可绑定的普通 ForEach 列表的以下视图工作正常,没有任何错误

@ObservedObject var notificationsViewModel = NotificationsViewModel.shared
//NotificationsViewModel does a API call and puts the fetched data in the Notifications Model


var body: some View {

VStack {
ForEach(notificationsViewModel.notifications?.notificationsDetails ?? [NotificationsDetail]()) { notificationsDetail in 
---additional code here--- }
}   

型号如下:

struct Notifications: Codable, Identifiable {
    
    let id = UUID()
    let numberOfNotifications: Int
    var notificationsDetails: [NotificationsDetail]

        enum CodingKeys: String, CodingKey {
            case numberOfNotifications = "number_of_notifications"
            case notificationsDetails = "notifications"
        }
}

struct NotificationsDetail: Codable, Identifiable, Equatable {
    let id: Int
    let notificationsCategoriesId: Int
    let questionsUsersName: String?
  
    enum CodingKeys: String, CodingKey {
        case id = "notifications_id"
        case notificationsCategoriesId = "notifications_categories_id"
        case questionsUsersName = "questions_users_name"
        
    }
}

当我尝试将此 ForEach 更改为可绑定的时,我开始收到多个错误。

ForEach($notificationsViewModel.notifications?.notificationsDetails ?? [NotificationsDetail]()) { $notificationsDetail in 
---additional code here using $notificationsDetail---}

当我尝试修复某些错误(如“删除?”)时,我收到一个新错误,提示我需要添加 ?。

当我删除默认值时?? NotificationsDetail,我仍然收到错误

Xcode 构建版本是 iOS15。

有谁知道如何解决这个问题?提前致谢。

ForEach($notificationsViewModel.notifications?.notificationsDetails ?? [NotificationsDetail]()

混淆了类型系统,因为 ?? 的一侧是对值数组的绑定,而另一侧是值数组。在你的关键路径中还有一个可选的使事情变得更复杂。

尝试重新排列 NotificationsViewModel 类型,使其只显示一个 non-optional 数组,而不是在视图级别出现所有这些可选的混乱。有一个可选的通知属性真的有意义吗,或者可以用一个空的代替吗?您需要单独的 notifications 结构吗?您是否只是直接根据 API 响应对数据类型进行建模?或许您可以更改模型类型以使其更易于使用?