Is it possible to iterate a dictionary inside ForEach in SwiftUI?

Viewed 308

I am trying to iterate a @Published dictionary from a viewModel in a view in SwiftUI. I get an error saying that:

Initializer 'init(_:id:content:)' requires that 'Dictionary<InterestDomain, Bool>.Keys' conform to 'RandomAccessCollection'

How can I iterate a dictionary inside a ForEach? this is my code:

ForEach(viewModel.userDomains.keys.indices, id: \.self) { index in
    VStack {
        DomainOfInterestElement(isActive: self.$isActive, domain: self.viewModel.userDomains.keys[index].name)
        if index != self.viewModel.domains.count - 1 {
            Divider().padding(.bottom, 12)
        }
    }
}.padding([.trailing, .leading], 12)
1 Answers

This is because a Dictionary is unordered. So its keys are unordered as well.

You need to make it ordered using Array:

ForEach(Array(viewModel.userDomains.keys).indices, id: \.self) { ...

As they are ordered randomly, you may also want to sort them:

ForEach(Array(viewModel.userDomains.keys).sorted().indices, id: \.self) { ...

But as the ordering and sorting gets more complex, you may think of moving the logic to the ViewModel instead.

Related