Home > Mobile >  Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Plan
Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Plan

Time:10-01

I'm currently building this an ios app and it seems that I have the following issue

Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Planet' conform to 'Identifiable'

This is my current code:

//
//  OnboadingView.swift
//  Planets (iOS)
//
//  Created by Andres Haro on 9/28/21.
//

import SwiftUI

struct OnboadingView: View {
    // Porperties
    
    var planets: [Planet] = planetsData
    
    
    // Body
    var body: some View {
        TabView{
            ForEach(planets[0...5]){ item in
                PlanetCardView(planet: <#Planet#>)
        } // Loop
    } // Tab
        
        .tabViewStyle(PageTabViewStyle())
        .padding(.vertical, 20)
    }
}

// Preview

struct OnboadingView_Previews: PreviewProvider {
    static var previews: some View {
        OnboadingView(planets: planetsData)
    }
}


Does anyone know what should I change on my code and why I'm getting that issue if I'm using the right reference from the right variable?

CodePudding user response:

ForEach needs to identify its contents in order to perform layout, successfully delegate gestures to child views and other tasks. Identifying the content means that there has to be some variable (which itself needs to conform to Hashable) that ForEach can use. In most cases, this is as simple as making your struct (Planet) conform to the Identifiable protocol. You did not provide implementation details of your Planets struct, but here is one way I could hink about that displays the point:

struct Planet: Identifiable {
    var id: String {
        self.name
    }
    var name: String
}

In this example, I'm assuming that the nam of a planet uniquely identifies it. Common ways of achieving this task are

  • Using UUID as identifier
  • Assigning a different integer (or using a static factory) to each new instance
  • Using an otherwise Hashable unique variable.

If you don't want to make your struct conform to Identifiable, you can also provide the variable you want this to be identified as as a key-path:

struct PlanetView: View {
    let planets: [Planet]

    var body: some View {
        ForEach(planets, id: \.name) { planet in
            //...
        }
    }
}
  • Related