SWIFTUI 调用键字典无法正常工作,并出现以下错误:“键路径中类型 '() -> Bool' 的下标索引必须是可哈希的”

Ces*_*lli 5 dictionary hashable swiftui

我有这样的看法:

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)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

将从视图中调用:

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
            }
        }
    }
}    
Run Code Online (Sandbox Code Playgroud)

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

为什么isSectionViewArray:[String:Bool] = [:]不是哈斯博?

如何修改工作代码?

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

Muh*_*ati 2

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

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
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)