Genérico SwiftUI Componente no puede deducir Hashable para CustomStringConvertible

0

Pregunta

Quiero crear un tipo genérico, que acepta todo lo que se ajusta a CustomStringConvertible y luego itera a través de los elementos.

Aquí está un ejemplo que destila por ese 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))

Así que me da un error Generic struct 'ForEach' requires that 'ItemType' conform to 'Hashable'

y Generic parameter 'Hashable' could not be inferred

Entonces, ¿qué estoy haciendo mal?

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

Mejor respuesta

1

Usted tiene la sintaxis 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

En otros idiomas

Esta página está en otros idiomas

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