ทั่วไป SwiftUI ส่วนประกอบไม่สามารถ infer Hashable สำหรับ CustomStringConvertible

0

คำถาม

ฉันต้องการเพื่อสร้างทั่วไปประเภทที่ยอมรับอะไรนั่น conforms ต้อง CustomStringConvertible และจากนั้น iterates นือพวกนั้นรายการ.

นี่คือเป็นตัวอย่างนั้น distils งนั้นปัญหา:

public struct Test<ItemType: CustomStringConvertible, Hashable>: View {
    var items: [ItemType]

    public var body: some View {
        ForEach(items, id: \.self) { item in
            Text("test")
        }
    }

}
let items: [String] = ["a", "b"]
let viewController = UIHostingController(rootView: Test(items: items))

ดังนั้นฉันได้ข้อผิดพลาด Generic struct 'ForEach' requires that 'ItemType' conform to 'Hashable'

แล้ว Generic parameter 'Hashable' could not be inferred

ดังนั้นฉันทำอะไรผิดเหรอ?

swiftui
2021-11-22 17:14:01
1

คำตอบที่ดีที่สุด

1

คุณมีรูปแบบการสั่งงานเรื่อง:

public struct Test<ItemType: CustomStringConvertible & Hashable>: View {   // <<: here!
    var items: [ItemType]

    public var body: some View {
        ForEach(items, id: \.self) { item in
            Text("test")
        }
    }

}
2021-11-22 17:20:18

ในภาษาอื่นๆ

หน้านี้อยู่ในภาษาอื่นๆ

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................