You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SwiftUI的ObservableObject中动态初始化对象数组?

问题解决方案

核心错误原因

  • 你混淆了 Swift 原生循环语法和 SwiftUI 视图组件:ForEach 是 SwiftUI 用于构建列表类视图的专属结构体,只能在 SwiftUI 视图的 body 代码块中使用,不能在 ViewModel 的普通业务方法里用作遍历逻辑,这是触发「Type '()' cannot conform to 'View'」错误的直接原因,业务逻辑遍历请用原生 for-in 循环。
  • 你的代码还存在几个隐性编译/逻辑问题:
    1. ViewModel 初始化方法中参数赋值错误,没有给实例属性 idValue 赋值
    2. setEndUserValues 方法中处理完的局部 users 数组没有赋值给 @Published 修饰的全局 users 属性,界面无法收到更新通知
    3. User 结构体遵守 Identifiable 协议但未定义 id 属性,初始化时传参会触发编译错误

修正后可运行代码

struct User: Identifiable {
    // 补上Identifiable协议要求的id属性
    var id: Int
    var profileName: String = ""
    var profileId: String = ""   
    var firstname: String = ""
    var lastname: String = ""
}

class ViewModel: ObservableObject {
    @Published var document: Document?
    @Published var users = [User]()
    var idValue: String

    init (idValue: String) {
        // 修正赋值逻辑,给实例属性赋值
        self.idValue = idValue
    }
    
    func getDetails() {
        APIService.shared.getDocumentDetails(idValue: idValue) { document in
            DispatchQueue.main.async {
                self.document = document
                self.setEndUserValues()
            }
        }
    }
    
    func setEndUserValues() {
        var tempUsers = [User]()
        if let document = document, let subjects = document.subjects {
            // 替换ForEach为原生for-in循环处理业务逻辑
            for index in 0..<subjects.count {
                let profile = subjects[index]
                var user = User(id: index)
                user.profileName = profile.profileName ?? ""
                user.profileId = profile.profileId ?? ""
                user.firstname = profile.firstname ?? ""
                user.lastname = profile.lastname ?? ""
                tempUsers.append(user)
            }
        }
        // 赋值给@Published属性,触发界面更新通知
        self.users = tempUsers
    }
}

内容的提问来源于stack exchange,提问作者user1960279

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:27:04