一般SwiftUI组无法推断可哈希于CustomStringConvertible

0

的问题

我想创建一个通用型的,就接受任何符合 CustomStringConvertible 然后重复这些项目。

这里是一个例子,蒸馏下问题:

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ý
..................................................................................................................