如何从 NSViewRepresentable / UIViewRepresentable 的协调器 class 中访问 EnvironmentObject?

How can I access an EnvironmentObject from within a NSViewRepresentable / UIViewRepresentable 's Coordinator class?

我得到了一个名为 appState 的 EnvironmentObject,它通过我的一些视图访问以共享数据/状态。我在视图中使用它们的方式是这样的:

struct MetalView: NSViewRepresentable {
@EnvironmentObject var appState: AppState

如何从我的视图的协调器访问 appState class?

当我尝试以我尝试过的任何方式调用它时,出现此错误:

“类型 'MetalView' 的实例成员 'appState' 不能用于嵌套类型 'MetalView.Coordinator' 的实例”

有什么线索吗?

这是我解决这个问题的方法:

AppState.swift:

class AppState: ObservableObject {
    
    static let shared = AppState()
    init () {} // TODO: was private init, find out if this has benefits
    
    @Published var currentView: String = "login"
    // add rest of shared stuff below

AppDelegate.swift:

func applicationDidFinishLaunching(_ aNotification: Notification) {
        let appState = AppState.shared

从 SwiftUI 视图访问:

struct ContentView: View {
    @EnvironmentObject var appState: AppState

从 NSViewRepresentable / UIViewRepresentable 协调器访问 Class:

class Coordinator: NSObject, MTKViewDelegate {
...  
        func draw(in view: MTKView) {
            ...
            context.render((AppState.shared.rawImage ?? AppState.shared.rawImageOriginal)!,
                to: drawable.texture,
                commandBuffer: commandBuffer,
                bounds: AppState.shared.rawImageOriginal!.extent,
                colorSpace: colorSpace)
    }
...

这花了我很多时间才弄明白,所以我希望它能帮助一些 SwiftUI 程序员的初学者...

如果高级程序员可以对此进行改进,请这样做,我可以从中学习。