首页 > 解决方案 > SWIFTUI 调用密钥字典不适用于错误:“密钥路径中的“() -> Bool”类型的下标索引必须是可散列的”

问题描述

我有这样的看法:

import SwiftUI

struct SectionView1: View {

    let dateStr:String    
    @Binding var isSectionView:Bool

    var body: some View {
        HStack {
            Button(action: {
                self.isSectionView.toggle()
            }) {
                Image(systemName: isSectionView ? "chevron.down.circle" : "chevron.right.circle")
            }
            Text("Media del \(dateStr)")
        }
    }
}

将从视图中调用:

import SwiftUI
import Photos

struct MediaView: View {
    let geoFolder:GeoFolderCD

    @State private var assetsForDate = [String :[PHAsset]]()
    @State private var isSectionViewArray:[String:Bool] = [:]

    var body: some View {
        List {
            ForEach(assetsForDate.keys.sorted(by: > ), id: \.self) { dateStr in
                Section {
                    SectionView1(dateStr: dateStr,
                                 isSectionView: self.$isSectionViewArray[dateStr, default: true])
                }
            }
        }
        .onAppear {
            self.assetsForDate = FetchMediaUtility().fetchGeoFolderAssetsForDate(geoFolder: geoFolderStruct, numAssets: numMediaToFetch)
            for dateStr in self.assetsForDate.keys.sorted() {
                self.isSectionViewArray[dateStr] = true
            }
        }
    }
}    

但我有错误:Subscript index of type '() -> Bool' in a key path must be HashableisSectionView: self.$isSectionViewArray[dateStr, default: true]

为什么isSectionViewArray:[String:Bool] = [:]没有 Hasbable?

怎样才能修改代码进行工作?

如果我删除, in SectionView, @Binding var isSectionView:Bool, 代码工作正常, 或者如果我设置, from SectionView, @Binding var isSectionViewArray:[String:Bool] = [:], 代码工作正常。

标签: dictionaryswiftuihashable

解决方案


您可以使用以下代码编写自己的绑定,它应该可以工作

var body: some View {
        List {
            ForEach(assetsForDate.keys.sorted(by: > ), id: \.self) { dateStr in
                let value = Binding<Bool>(get: { () -> Bool in
                    return self.isSectionViewArray[dateStr, default: true]
                }) { (value) in

                }
                Section {
                    SectionView1(dateStr: dateStr,
                                 isSectionView: value)
                }
            }
        }
        .onAppear {
            self.assetsForDate = FetchMediaUtility().fetchGeoFolderAssetsForDate(geoFolder: geoFolderStruct, numAssets: numMediaToFetch)
            for dateStr in self.assetsForDate.keys.sorted() {
                self.isSectionViewArray[dateStr] = true
            }
        }
    }

推荐阅读