[SwiftUI]:ForEach 不适用于字典数组、带数组的字典

Posted

技术标签:

【中文标题】[SwiftUI]:ForEach 不适用于字典数组、带数组的字典【英文标题】:[SwiftUI]: ForEach is not working for array of dictionary, dictionary with array 【发布时间】:2020-03-17 13:00:56 【问题描述】:

我尝试在 SwiftUI 中遍历数组,但它不能正常工作。

我的代码:

let arr_type2  = [
                    ["type":"Temperature","Units":["°C","°F","°K"]],
                    ["type":"Length","Units":["m","km","ft","yd","mi"]],
                    ["type":"Time","Units":["sec","min","hr","day"]],
                    ["type":"Volume","Units":["ml","lt","cups","pints","gallons"]]
                    ]

ForEach(arr_type2, id: \.self)  dict in //Error
        Text("")

错误:协议类型“Any”不能符合“Hashable”,因为只有具体类型才能符合协议

我刚开始学习 SwiftUI,你能帮我保存一下吗?

感谢您宝贵的时间!

【问题讨论】:

【参考方案1】:

你可以干净利落地写出来

struct Model:Hashable 
    let type:String
    let unnits:[String]


struct ContentView: View 

    let arr_type2 = [Model(type:"Temperature", unnits: ["°C","°F","°K"])]

    var body: some View 
           ForEach(arr_type2, id: \.self)  item in

            Text(item.type)
        
    

为什么检查https://www.hackingwithswift.com/books/ios-swiftui/why-does-self-work-for-foreach

【讨论】:

【参考方案2】:

你可以像这样使用ForEach

 var body: some View 
    let arr_type2  = [
        ["type":"Temperature","Units":["°C","°F","°K"]],
        ["type":"Length","Units":["m","km","ft","yd","mi"]],
        ["type":"Time","Units":["sec","min","hr","day"]],
        ["type":"Volume","Units":["ml","lt","cups","pints","gallons"]]
    ]

    return ForEach(0..<arr_type2.count, id: \.self)  index -> AnyView in
        let units = arr_type2[index]["Units"] as! [String]
        return AnyView(VStack 
            Text(arr_type2[index]["type"] as! String)
            ForEach(0..<units.count, id: \.self)  indexUnits in
                 Text(units[indexUnits])
            

        )
    


【讨论】:

它显示错误,例如“对成员'count'的模糊引用” @NiravPatel 请看我的编辑,这会显示每个字典中的“类型”,在 Xcode 11.3 中测试 谢谢,但我忘记了之前的问题?另外,之后如何使用相同的 ForEach 遍历 Units? @NiravPatel 您方法中的问题是 arr_type2 的类型必须是可散列的(字典不是可散列的)。 “单位”是数组,因此您需要另一个 ForEach 来迭代它们,请参阅我编辑的答案

以上是关于[SwiftUI]:ForEach 不适用于字典数组、带数组的字典的主要内容,如果未能解决你的问题,请参考以下文章

使用 ForEach (SwiftUI) 的偶数行和奇数行

SwiftUI ForEach 的字典识别问题

SwiftUI 使用 List 和 Foreach 遍历字典中的键并创建列表视图

SwiftUI - AppStorage 不适用于 GeometryReader

动画不适用于 SwiftUI 视图状态更改

SwiftUI 深色模式不适用于工作表