在“ForEach”上引用初始值设定项“init(_:content:)”要求“Planet”符合“可识别”

Hva*_*res 6 list ios swift swiftui

我目前正在构建一个 ios 应用程序,似乎有以下问题

Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Planet' conform to 'Identifiable'
Run Code Online (Sandbox Code Playgroud)

这是我当前的代码:

//
//  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)
    }
}


Run Code Online (Sandbox Code Playgroud)

有谁知道我应该对代码进行哪些更改,以及如果我使用正确变量中的正确引用,为什么会遇到该问题?

Sch*_*tky 14

ForEach需要识别其内容才能执行布局、成功地将手势委托给子视图和其他任务。识别内容意味着必须有一些变量(其本身需要符合HashableForEach可以使用。在大多数情况下,这就像使您的 struct ( Planet) 符合Identifiable协议一样简单。您没有提供Planets 结构的实现细节,但这是我可以想到的显示要点的一种方法:

struct Planet: Identifiable {
    var id: String {
        self.name
    }
    var name: String
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,我假设行星的名称唯一标识它。完成此任务的常见方法是

  • 用作UUID标识符
  • 为每个新实例分配不同的整数(或使用静态工厂)
  • 使用其他Hashable唯一的变量。

如果您不想使您的结构符合Identifiable,您还可以提供您希望将其标识为键路径的变量:

struct PlanetView: View {
    let planets: [Planet]

    var body: some View {
        ForEach(planets, id: \.name) { planet in
            //...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)