我想在struct: User中添加一个类型为View的变量,然后向用户添加单独的视图(如Manuelle所示)。然而,我得到的错误“协议‘视图’只能作为一个通用约束,因为它有自或相关的类型要求”和“类型‘’用户‘不符合协议’赤道‘/哈斯可”。
struct User : Hashable {
let name: String
let age: Int
let profilePicture, status, icon: String
let view: View
}
struct MyUserView: View {
let users = [
User(name: "Manuelle", age: 23, profilePicture: "person", status: "inactive", icon: "message.fill", view: UserProfileView()),
User(name: "Michael", age: 39, profilePicture: "person", status: "active 12 minutes ago", icon: "square.on.square")
]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
HStack {
Text(user.name)
Image(systemName: user.profilePicture)
}
}
}
}
}
}发布于 2022-06-23 22:26:59
从let view: View结构中删除User,这是主要问题。
另外,不能将id: \.self提供给ForEach视图。id必须是作为结构的唯一标识符的属性,它不能是结构本身,因为当结构数组发生变化时,会发生崩溃。您可以选择几个方法来修复它:
ForEach(users, id: \.name) { user in或更好:
struct User : Identifiable {
var id: String {
return name
}因为这样你就可以简单地做:
ForEach(users) { user in但通常我们会这样做:
struct User : Identifiable {
let id = UUID()当然,除非userID来自服务器。
https://stackoverflow.com/questions/72735722
复制相似问题