中另一个对象的参数

中另一个对象的参数

本文介绍了StateObject 作为 init() 中另一个对象的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试将 StateObject 用户传递给 authenticationHelper,但我不能,因为 IDE 说在初始化所有存储的属性之前使用 self",即使它在结构的开头初始化.我想过将用户的初始化移动到 init() 但同样,我不能,因为它是一个 get-only 属性,它必须立即初始化.有解决办法吗?

I'm trying to pass the StateObject user to the authenticationHelper but I can't since the IDE says that 'self is used before all stored properties are initialized', even though it is initialized at the beginning of the struct. I thought about moving the initialization of user to init() but again, I can't since it's a get-only property and it has to be initialized immediately. Is there a work around?

@main
struct Test: App {
    @StateObject var user: User = User()
    var authenticationHelper: AuthenticationHelper

    init(){
        self.authenticationHelper = AuthenticationHelper(user: user)
    }

    var body: some Scene {
        WindowGroup {
            LoginView(user: user)
        }
    }
}

推荐答案

使用计算属性

struct Test: App {

    @StateObject var user: User = User()
    var authenticationHelper: AuthenticationHelper {
        return AuthenticationHelper(user: user)
    }

    init() {
    }
}

你也可以这样使用

struct Test: App {

    @StateObject var user: User
    var authenticationHelper: AuthenticationHelper

    init() {
        let user = User()
        self._user = StateObject(wrappedValue: user)
        self.authenticationHelper = AuthenticationHelper(user: user)
    }
}

这篇关于StateObject 作为 init() 中另一个对象的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:29