【发布时间】:2021-03-17 17:40:11
【问题描述】:
我正在尝试将结构作为泛型类型传递(见模型)。我尝试使用 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 中使用什么类型来表示泛型中的结构?
型号:
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())
}
}
}
【问题讨论】: