如何访问 class 中的全局环境对象?

How to access a global environment object in a class?

我有一个 class 需要更新全局环境对象。我可以整天在我的结构之间传递那个环境对象,但是我如何允许 class 对象访问同一个变量?

import SwiftUI

class Global: ObservableObject
{
    @Published var num = 10
}

class MyClass:ObservableObject
{
    @Published var mode = 1
    @EnvironmentObject var global: Global

    func updateMode()
    {
        self.mode += 1
        global.num += 1
    }
}

@main
struct MyApp: App
{
    let settings = Global()
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(settings)
            }
    }
}

struct ContentView: View
{
    @EnvironmentObject var global: Global
    @ObservedObject var myClass = MyClass()
    
    var body: some View
    {
        VStack
        {
            Text("Setting \(global.num)")
            Text("Mode \(myClass.mode)")

            Button("Click Me", action: {myClass.updateMode()})
        }
        .padding()
    }
}

以下代码报错:

Fatal Error: No ObservableObject of type Global found. A View.environmentObject(_:) for Global maybe missing an ancestor of this view.

我可以将全局对象传递给 myClass.updateMode,但那时它似乎不是很全局?我还以为一定有更好的办法呢

一种可能的方法是使其共享(并且不要在 SwiftUI 视图之外的任何地方使用 @EnvironmentObject - 它不是为此设计的):

class Global: ObservableObject
{
    static let shared = Global()

    @Published var num = 10
}

class MyClass:ObservableObject
{
    @Published var mode = 1
    let global = Global.shared    // << here !!

// ...
}

@main
struct MyApp: App
{
    @StateObject var settings = Global.shared  // << same !!
// ...
}