Všeobecné SwiftUI Komponent nemôže vyvodiť Hashable pre CustomStringConvertible

0

Otázka

Chcem vytvoriť všeobecný typ, ktorý akceptuje čokoľvek, čo vyhovuje CustomStringConvertible a potom iterates cez tieto položky.

Tu je príklad, ktorý destiluje sa ustanovuje, že 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 som sa zobrazí chybové hlásenie Generic struct 'ForEach' requires that 'ItemType' conform to 'Hashable'

a Generic parameter 'Hashable' could not be inferred

Takže to, čo robím zle?

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

Najlepšiu odpoveď

1

Máte syntax vydania:

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 iných jazykoch

Táto stránka je v iných jazykoch

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