用另一个StateObject初始化StateObject

时间:2020-10-10 09:01:32

标签: swiftui

我有这个App结构,我需要在其中使用userManager来初始化AppearsStore和behavioursStore。 但是我收到错误Escaping auto closure captures mutating 'self' parameterVariable 'self.appearancesStore' captured by a closure before being initialized

我尝试了一些不同的方法来执行此操作,但是都失败了。 有没有人建议如何做?

@main
struct DuneApp: App {
    @StateObject var userManager = UserManager()
    @StateObject var appearancesStore: AppearancesStore
    @StateObject var behavioursStore: BehavioursStore

    init() {
        _appearancesStore = StateObject(wrappedValue: AppearancesStore(manager: self.userManager))
        _behavioursStore = StateObject(wrappedValue: BehavioursStore(manager: self.userManager))
    }

    var body: some Scene {
        WindowGroup {
            AuthenticateView()
                .environmentObject(userManager)
                .environmentObject(appearancesStore)
                .environmentObject(behavioursStore)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

尝试以下

@main
struct DuneApp: App {
    @StateObject var userManager: UserManager
    @StateObject var appearancesStore: AppearancesStore
    @StateObject var behavioursStore: BehavioursStore

    init() {
        let userManager = UserManager()

        _userManager = StateObject(wrappedValue: userManager)
        _appearancesStore = StateObject(wrappedValue: AppearancesStore(manager: userManager))
        _behavioursStore = StateObject(wrappedValue: BehavioursStore(manager: userManager))
    }

    var body: some Scene {
        WindowGroup {
            AuthenticateView()
                .environmentObject(userManager)
                .environmentObject(appearancesStore)
                .environmentObject(behavioursStore)
        }
    }
}