SwiftUI报错:无法将Notifications.Type转换为预期类型Notifications
解决“Cannot convert value of type 'Notifications.Type' to expected argument type 'Notifications'”错误
问题核心
你传递给ProfileSummary的是Notifications类型本身,而不是它的实例对象,导致类型不匹配。
具体修复步骤
1. 修正ModelData中notifications的定义
打开你的ModelData代码,确保notifications是Notifications的实例,而非类型本身:
// 错误示例:把类型赋值给变量 var notifications: Notifications.Type = Notifications.self // 正确示例:声明并初始化一个Notifications实例 var notifications: Notifications = Notifications()
如果是从Firebase获取数据,要将解析后的实例赋值给该变量,而不是直接使用类型。
2. 确认ProfileSummary的参数类型
检查ProfileSummary的初始化方法,确保它接收的是Notifications实例:
struct ProfileSummary: View { // 正确:接收Notifications实例 let notifications: Notifications // 其他代码... }
3. 修正ProfileSummary的调用代码
在ProfileHost中调用ProfileSummary时,传递modelData里的Notifications实例:
// 错误示例:传递了类型本身 ProfileSummary(notifications: Notifications.self) // 正确示例:传递实例对象 ProfileSummary(notifications: modelData.notifications)
4. Firebase数据解析补充(如果涉及)
如果是从Firebase拉取数据后赋值,要将返回的数据解析为Notifications实例:
// 假设Notifications遵循Codable协议 if let snapshotData = snapshot.value as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: snapshotData), let notifications = try? JSONDecoder().decode(Notifications.self, from: data) { modelData.notifications = notifications }
内容的提问来源于stack exchange,提问作者Advik Saxena
相关产品推荐
相关产品推荐

