![](/img/trans.png)
[英]Value of protocol type 'Any' cannot conform to 'Equatable'; only struct/enum/class types can conform to protocols
[英]"Type 'User' does not conform to protocol 'Equatable'/ 'Hashable'
我想在我的結構中添加一個 View 類型的變量:User,然后再向我的用戶添加單個視圖(如 Manuelle 所示)。 但是我收到錯誤“協議'視圖'只能用作通用約束,因為它具有自身或關聯的類型要求”和“類型'用戶'不符合協議'Equatable'/ Hashable”。
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)
}
}
}
}
}
}
從User
結構中刪除let view: View
,這是主要問題。
此外,您不能將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()
當然,除非用戶 ID 來自服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.