Generico SwiftUI Componente non può dedurre Hashable per CustomStringConvertible

0

Domanda

Voglio creare un tipo generico, che accetta tutto ciò che è conforme alla CustomStringConvertible e poi l'iterazione di questi elementi.

Qui è un esempio che riassume giù quel problema:

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

Così ottengo un errore Generic struct 'ForEach' requires that 'ItemType' conform to 'Hashable'

e Generic parameter 'Hashable' could not be inferred

Così che cosa sto facendo di sbagliato?

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

Migliore risposta

1

Hai sintassi problema:

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

In altre lingue

Questa pagina è in altre lingue

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