[英]Generic type of a struct - SwiftUI
我正在尝试将结构作为泛型类型(在模型中看到)传递。 我尝试使用 AnyView 来表示我的结构,但是编译器在构建时出错:
Could not cast value of type 'EagleNation_macOS.NewsView' (0x10d7ff898) to 'SwiftUI.AnyView' (0x7fff82e27670).
2021-03-17 12:35:45.932135-0500 EagleNation-macOS[24102:2436828] Could not cast value of type 'EagleNation_macOS.NewsView' (0x10d7ff898) to 'SwiftUI.AnyView' (0x7fff82e27670).
Could not cast value of type 'EagleNation_macOS.NewsView' (0x10d7ff898) to 'SwiftUI.AnyView' (0x7fff82e27670).
我用什么类型来表示 SwiftUI 中的泛型结构?
Model:
import Foundation
struct MainBackend<Destination> {
let navDirs = [
NavDir(title: "News", dest: NewsView() as! Destination),
NavDir(title: "Bulletin", dest: BulletinView() as! Destination),
NavDir(title: "Clubs", dest: ClubsView() as! Destination),
]
struct NavDir: Identifiable {
let title: String
let dest: Destination
var id = UUID()
}
}
视图模型:
import SwiftUI
class MainCommunication {
private var backend = MainBackend<AnyView>()
// MARK: - Access to Model
var navDirs: [MainBackend<AnyView>.NavDir] {
backend.navDirs
}
}
看法:
import SwiftUI
struct MainView: View {
var body: some View {
NavigationView {
NavBar { NavDir in
NavDir.dest
}
NewsView()
}
}
}
struct NavBar<Destination: View>: View {
let navDirs = MainCommunication().navDirs
let buildDestination: (MainBackend<AnyView>.NavDir) -> Destination
var body: some View {
VStack() {
List(navDirs) { NavDir in
NavigationLink(destination: buildDestination(NavDir)) {
Text(NavDir.title)
}
}
.listStyle(SidebarListStyle())
}
}
}
您将希望它们成为AnyView
- 这是将类型擦除到同质数组中的唯一方法。 但是,您不能转换为AnyView
- 您必须将它们包装在AnyView()
中。
这意味着您实际上根本不需要泛型:
struct MainBackend {
let navDirs = [
NavDir(title: "News", dest: AnyView(NewsView())),
NavDir(title: "Bulletin", dest: AnyView(BulletinView())),
NavDir(title: "Clubs", dest: AnyView(ClubsView())),
]
struct NavDir: Identifiable {
let title: String
let dest: AnyView
var id = UUID()
}
}
class MainCommunication {
private var backend = MainBackend()
// MARK: - Access to Model
var navDirs: [MainBackend.NavDir] {
backend.navDirs
}
}
struct MainView: View {
var body: some View {
NavigationView {
NavBar { NavDir in
NavDir.dest
}
}
}
}
struct NavBar<Destination: View>: View {
let navDirs = MainCommunication().navDirs
let buildDestination: (MainBackend.NavDir) -> Destination
var body: some View {
VStack() {
List(navDirs) { NavDir in
NavigationLink(destination: buildDestination(NavDir)) {
Text(NavDir.title)
}
}
.listStyle(SidebarListStyle())
}
}
}
另请参阅: 如何使用 SwiftUI 获得动态视图列表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.