繁体   English   中英

在 'ForEach' 上引用初始化程序 'init(_:content:)' 要求 'Pl.net' 符合 'Identifiable'

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

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

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

这是我当前的代码:

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


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

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

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

在此示例中,我假设 pl.net 的名称唯一标识它。 完成这项任务的常用方法是

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

如果您不想让您的结构符合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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM