Generic SwiftUI Součást nelze odvodit Hashable pro CustomStringConvertible

0

Otázka

Chci vytvořit obecný typ, který přijímá cokoliv, co splňuje CustomStringConvertible a pak iteruje přes tyto položky.

Zde je příklad, který padá dolů tento problém:

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))

Tak jsem si chybu Generic struct 'ForEach' requires that 'ItemType' conform to 'Hashable'

a Generic parameter 'Hashable' could not be inferred

Takže co dělám špatně?

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

Nejlepší odpověď

1

Máte syntaxe vydání:

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

V jiných jazycích

Tato stránka je v jiných jazycích

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