在swiftUI中初始化变量

时间:2020-07-29 17:59:15

标签: swiftui

我是swiftUI的新手,听说这是应用程序开发的最短路径。但是我在给变量赋值时遇到了一些困难。以下代码段让我感到困惑。

self.phone = fetcher.customer!.phone 
print( self.phone )                <-- Empty string 
print( fetcher.customer!.phone )   <-- 555-555-5555

全视图:

struct WithCustomer: View {
    @ObservedObject var fetcher: CustomerFetcher
    @State private var first_name: String = ""
    @State private var last_name: String  = ""
    @State private var email: String      = ""
    @State private var phone: String      = ""
    
    init( fetcher: CustomerFetcher ) {
        self.fetcher    = fetcher
        self.first_name = fetcher.customer!.first_name
        self.last_name  = fetcher.customer!.last_name
        self.email      = fetcher.customer!.email
        self.phone      = fetcher.customer!.phone
        print( self.phone )
        print( fetcher.customer!.phone )
    }
    var body: some View {
        NavigationView {
            Form {
                TextField("First name", text: self.$first_name)
                TextField("Last name",  text: self.$last_name )
                TextField("email", text: self.$email )
                TextField( "phone", text: self.$phone )
            }.navigationBarTitle(Text("Profile"))
        }
    }
    
}

我确定我只是忘记对超类的第二次实例化或某些东西强制强制解开包装,但是任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

状态属性应以不同的方式初始化。这是phone

的示例
struct WithCustomer: View {
    @ObservedObject var fetcher: CustomerFetcher

    // ... other state should be declared similarly

    @State private var phone: String   // << no assign, only declare
    
    init( fetcher: CustomerFetcher ) {
        self.fetcher    = fetcher

        // ... other state should be initialised similarly

        self._phone = State(initialValue: fetcher.customer!.phone)
    }

    // .. other code