[英]Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'Planet' conform to 'Identifiable'
I'm currently building this an ios app and it seems that I have the following issue我目前正在构建一个 ios 应用程序,似乎我遇到了以下问题
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?有谁知道我应该对我的代码进行哪些更改,以及如果我使用来自正确变量的正确引用,为什么会遇到这个问题?
ForEach
needs to identify its contents in order to perform layout, successfully delegate gestures to child views and other tasks. ForEach
需要识别其内容以执行布局、成功地将手势委托给子视图和其他任务。 Identifying the content means that there has to be some variable (which itself needs to conform to Hashable
) that ForEach
can use.识别内容意味着必须有一些ForEach
可以使用的变量(它本身需要符合Hashable
)。 In most cases, this is as simple as making your struct ( Pl.net
) conform to the Identifiable
protocol.在大多数情况下,这就像让您的结构 ( Pl.net
) 符合可Identifiable
协议一样简单。 You did not provide implementation details of your Pl.net
s struct, but here is one way I could hink about that displays the point:您没有提供Pl.net
结构的实现细节,但这是我可以想到的一种方式,它显示了这一点:
struct Planet: Identifiable {
var id: String {
self.name
}
var name: String
}
In this example, I'm assuming that the nam of a pl.net uniquely identifies it.在此示例中,我假设 pl.net 的名称唯一标识它。 Common ways of achieving this task are完成这项任务的常用方法是
UUID
as identifier使用UUID
作为标识符Hashable
unique variable.使用其他Hashable
唯一变量。 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:如果您不想让您的结构符合Identifiable
,您还可以提供您希望将其标识为键路径的变量:
struct PlanetView: View {
let planets: [Planet]
var body: some View {
ForEach(planets, id: \.name) { planet in
//...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.