![](/img/trans.png)
[英]SwiftUI - Error - Initializer 'init(_:rowContent:)' requires that 'CustomDataModel' conform to 'Identifiable'
[英]Initializer `init(:_rowContent:)` requires that `Type` confirm to `Identifiable`
我正在關注KMM 教程,並且能夠在 Android 端成功運行該應用程序。 現在我想測試 iOS 部分。 一切似乎都很好,除了下面的編譯錯誤。 我想這一定是一件微不足道的事情,但由於我對 iOS/Swift 的經驗為零,我正在努力修復它。
我的第一次嘗試是讓RocketLaunchRow
擴展Identifiable
,但后來我遇到了其他問題......不勝感激。
xcode 版本:12.1
完整來源:
import SwiftUI
import shared
func greet() -> String {
return Greeting().greeting()
}
struct RocketLaunchRow: View {
var rocketLaunch: RocketLaunch
var body: some View {
HStack() {
VStack(alignment: .leading, spacing: 10.0) {
Text("Launch name: \(rocketLaunch.missionName)")
Text(launchText).foregroundColor(launchColor)
Text("Launch year: \(String(rocketLaunch.launchYear))")
Text("Launch details: \(rocketLaunch.details ?? "")")
}
Spacer()
}
}
}
extension RocketLaunchRow {
private var launchText: String {
if let isSuccess = rocketLaunch.launchSuccess {
return isSuccess.boolValue ? "Successful" : "Unsuccessful"
} else {
return "No data"
}
}
private var launchColor: Color {
if let isSuccess = rocketLaunch.launchSuccess {
return isSuccess.boolValue ? Color.green : Color.red
} else {
return Color.gray
}
}
}
extension ContentView {
enum LoadableLaunches {
case loading
case result([RocketLaunch])
case error(String)
}
class ViewModel: ObservableObject {
let sdk: SpaceXSDK
@Published var launches = LoadableLaunches.loading
init(sdk: SpaceXSDK) {
self.sdk = sdk
self.loadLaunches(forceReload: false)
}
func loadLaunches(forceReload: Bool) {
self.launches = .loading
sdk.getLaunches(forceReload: forceReload, completionHandler: { launches, error in
if let launches = launches {
self.launches = .result(launches)
} else {
self.launches = .error(error?.localizedDescription ?? "error")
}
})
}
}
}
struct ContentView: View {
@ObservedObject private(set) var viewModel: ViewModel
var body: some View {
NavigationView {
listView()
.navigationBarTitle("SpaceX Launches")
.navigationBarItems(trailing:
Button("Reload") {
self.viewModel.loadLaunches(forceReload: true)
})
}
}
private func listView() -> AnyView {
switch viewModel.launches {
case .loading:
return AnyView(Text("Loading...").multilineTextAlignment(.center))
case .result(let launches):
return AnyView(List(launches) { launch in
RocketLaunchRow(rocketLaunch: launch)
})
case .error(let description):
return AnyView(Text(description).multilineTextAlignment(.center))
}
}
}
在不符合 Identifiable 協議的原始類型上使用 List 或 ForEach,例如字符串或整數數組。 在這種情況下,您應該使用 id: .self 作為 List 或 ForEach 的第二個參數
從上面我們可以看出,您需要在發生錯誤的那一行執行此操作:
return AnyView(List(launches, id: \.self) { launch in
我認為這應該消除你的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.