无法将元组传递到列表视图

Cannot Pass Tuples into List View

我有一个 UI 是使用 StoryBoard 构建的应用程序,我现在正在尝试将其转换为 SwiftUI。我遇到的问题是该应用程序主要由通过 Tableviews 传递的元组数据数组组成。然而,在 SwiftUI 中,我找不到将元组数据传递到列表视图的方法。我不断收到以下错误消息:

Type '(String, String, String)' cannot conform to 'Hashable'; only struct/enum/class types can conform to protocols.

我尝试通过结构传递我的元组数组,看看我是否可以让它以这种方式工作,但无法通过结构有效地解码元组数组。谁有想法?我目前的代码如下:

struct Result: View {
    
    let tupleArray = [("a", "z", "c"), ("e", "x", "d"), ("c", "y", "x")]

    var body: some View {
        NavigationView {
            List {
                ForEach(self.tupleArray, id: \.self) { item in
                    ResultsRowView(text0: item.0, text1: item.1, text2: item.2)
                }
            }//:LOOP
        }
    }
} 

我的列表行视图如下:

struct ResultsRowView: View {
    
    var text0 = "a"
    var text1 = "b"
    var text2 = "c"
    
    var body: some View {
        HStack(alignment: .center) {
            Text(text0)
            Text(text1)
            Text(text2)
        } //:HSTACK
    }
}

在 Swift 中,元组不能符合 Hashable - 参见 How do I make (Int,Int) Hashable?

你得到的错误正是这样说的:

only struct/enum/class types can conform to protocols.

一个可能的解决方案是创建一个符合 Hashable:

的自定义结构
struct Model: Hashable {
    let item1: String
    let item2: String
    let item3: String
}

并像这样使用它:

struct Result: View {
    let tupleArray = [("a", "z", "c"), ("e", "x", "d"), ("c", "y", "x")]
        .map(Model.init)

    var body: some View {
        NavigationView {
            List {
                ForEach(self.tupleArray, id: \.self) { item in
                    ResultsRowView(text0: item.item1, text1: item.item2, text2: item.item3)
                }
            }
        }
    }
}

注意:您可以使用 .map(Model.init) 轻松地将元组数组转换为模型对象数组。