【问题标题】:Cannot Pass Tuples into List View无法将元组传递到列表视图
【发布时间】:2021-01-07 22:49:50
【问题描述】:

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

类型'(String, String, String)' 不能符合'Hashable';只要 struct/enum/class 类型可以符合协议。

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

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 struct swiftui tuples swiftui-list


    【解决方案1】:

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

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

    只有结构/枚举/类类型可以符合协议。

    一种可能的解决方案是创建一个符合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) 轻松地将元组数组转换为模型对象数组。

    【讨论】:

      猜你喜欢
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      相关资源
      最近更新 更多