swiftswiftuiswift-dictionary

How use use SwiftUI ForEach with a dictionary [ customEnum : customStrut ] - getting "conform to 'RandomAccessCollection'" error


How could I correct this code from failing build? Basically wanting to use ForEach to iterate through a dictionary which is based on a [ customEnum : customStrut ].

Otherwise if this is problematic a different way to achieve that SwiftUI supports?

Errors

Referencing initializer 'init(_:id:content:)' on 'ForEach' requires that '[GCFilterViewOptions.FilterOptions : GCFilterViewOptions.FilterOptionValues]' conform to 'RandomAccessCollection'

Type '(key: GCFilterViewOptions.FilterOptions, value: GCFilterViewOptions.FilterOptionValues)' cannot conform to 'Hashable'; only struct/enum/class types can conform to protocols

Code

import SwiftUI

struct GCFilterViewOptions: View {
    enum FilterOptions {
        case NewLine
        case Comma
        case Space
    }
    struct FilterOptionValues {
        var title : String
        var selected : Bool
    }
    var filterSelections : [FilterOptions : FilterOptionValues] = [
        FilterOptions.NewLine : FilterOptionValues(title: "New Line", selected: true),
        FilterOptions.Comma : FilterOptionValues(title: "Comma", selected: true),
        FilterOptions.Space : FilterOptionValues(title: "Space", selected: false)
    ]

    var body : some View {
        HStack {
            ForEach(filterSelections, id:\.self) { filterOption in.  // ** ERRORS HERE **
                Text("TBD")
                // Will be putting checkboxes here - i.e. so can chose which ones 
            }
        }
    }
}

Solution

  • As states dictionary is not "random access" capable collection, so it cannot be used directly in ForEach, here is possible approach

    HStack {
        ForEach(Array(filterSelections.keys.enumerated()), id:\.element) { _, key in
            Text("TBD \(self.filterSelections[key]?.title ?? "")")
            // Will be putting checkboxes here - i.e. so can chose which ones
        }
    }