sin tribu
sin tribu

Reputation: 1180

initializing variables in swiftUI

I am new to swiftUI and heard it's the shortest path to app development. But I'm having some difficulties with assigning a value to a variable. The following snippet is where I'm perplexed.

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

And full view:

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"))
        }
    }
    
}

I'm sure I'm just forgetting to force a coercive unwrap on the views second instantiation of the super class or something but any help would be appreciated. Thanks.

Upvotes: 2

Views: 1419

Answers (1)

Asperi
Asperi

Reputation: 257493

State properties should be initialised differently. Here is an example for 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

Upvotes: 1

Related Questions