У меня есть свойство @State
(в примере @State var parent: Parent
) со свойством массива, которое я хочу перебрать в ForEach
l oop в SwiftUI. Это прекрасно работает, когда я
ForEach(parent.children, id: \.self) { child in
ChildView(child: child)
}
, хотя я считаю, что добавление $
к вызову правильно передает его дочернему представлению . Однако тогда я получаю ошибку Unable to infer complex closure return type; add explicit type to disambiguate
.
Как правильно решить эту проблему и почему этот код неверен?
Минимальный код для воспроизведения
import UIKit
import SwiftUI
func setup() -> Parent {
let child = Child(name: "foo")
let parent = Parent(name: "bar")
parent.children = [child]
return parent
}
class Parent {
var name: String
var children: [Child] = []
init(name: String) {
self.name = name
}
}
class Child: Hashable {
static func == (lhs: Child, rhs: Child) -> Bool {
lhs.name == rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.name)
}
var name: String
init(name: String) {
self.name = name
}
}
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let parent = setup()
let parentView = ParentView(parent: parent)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: parentView)
self.window = window
window.makeKeyAndVisible()
}
}
}
struct ChildView: View {
@State var child: Child
var body: some View {
VStack {
Text("Child “\(child.name)”")
}
}
}
struct ParentView: View {
@State var parent: Parent
var body: some View {
VStack {
Text("Parent “\(parent.name)”")
// ForEach($parent.children, id: \.self) { child in
// Yields error:
// Unable to infer complex closure return type; add explicit type to disambiguate
ForEach(parent.children, id: \.self) { child in
ChildView(child: child)
}
}
}
}
struct ParentView_Previews: PreviewProvider {
static var previews: some View {
let parent = setup()
return ParentView(parent: parent)
}
}