iOS Development

ios – SwiftUI looping by an array of Any utilizing a ForEach – Kind ‘any ‘ can’t conform to ‘Identifiable’

Spread the love

I’ve created a protocol as follows:

protocol InputViewModel: ObservableObject, Identifiable {
    var id: UUID { get }
    var title: String { get }
    var shouldShowTitle: Bool { get }
    var information: String { get set }
    var placeholder: String { get }
    var fieldType: FieldType { get }

Utilizing this protocol, I’ve created sorts like TextFieldViewModel, TextViewViewModel, DatePickerViewModel and so on

In my SwiftUI view, I’ve a listing which may have any enter sort so I’ve an array as follows:

non-public(set) var inputViewModels: [any InputViewModel] = []

I populate this with required view fashions.

Now in my SwiftUI view, I wish to loop by these view fashions and construct the UI so I do that:

Record {
    ForEach(currentProjectViewModel.projectInfoViewModels) { inputViewModel in
        if let inputViewModel = inputViewModel as? TextFieldRowViewModel {
            createUI(inputViewModel: inputViewModel)

That is the place I get the error Kind 'any InputViewModel' can't conform to 'Identifiable'

SwiftUI error looping to any type

I do know one approach to repair this might be to make the inputViewModels of a selected sort so that may be non-public(set) var inputViewModels: [InputViewModel] = [] with out the usage of any, nonetheless, I do have the requirement to help any enter sort.

One other resolution can be to make use of indices as follows

ForEach(currentProjectViewModel.projectInfoViewModels.indices, id: .self) { index in
    let viewModel = currentProjectViewModel.projectInfoViewModels[index]
    if let inputViewModel = viewModel as? TextFieldRowViewModel {
        createUI(inputViewModel: inputViewModel)

Nevertheless, I’ve heard that utilizing indices just isn’t actually dependable in SwiftUI views and as a lot as attainable we wish to iterate over the article

I additionally got here throughout this reply however it’s much like the primary resolution I identified right here.

How may I obtain what I would like within the easiest / cleanest manner attainable ?

Leave a Reply

Your email address will not be published. Required fields are marked *