Search code examples
swiftuitextfieldoption-typeobservedobject

Swiftui - TextField with optional observedObject


Here I have view with a textfield that reads off an ObservedObject. The Observed object has a property called "user" that is of optional type "NewUser?". When I try to unwrap the "NewUser" to retrieve its username for the textfied I get an error saying that I must still unwrap it.

The Errors

NewUser Model

struct NewUser: {
    var id: UUID?
    var username: String
}

Observed Object

class HTTPUserClient: ObservableObject {
    
    @Published var user: NewUser? //a user struct with a non optional 
    //function and stuff ommitted
}

View

import SwiftUI

struct TestUserEditor: View {
    @ObservedObject var userClient:HTTPUserClient
    
    var body: some View {
        TextField("required", text: $userClient.user!.username)   
    } 
}    

The errors

IF I use the above code I get the following error

Value of optional type 'NewUser?' must be unwrapped to refer to member 'firstName' of wrapped base type 'NewUser'

but if I fix it by adding a "!", force unwrapping the user, I get the same error


Solution

  • My suggestion is to get rid of the optional by adding a static example as a placeholder.

    struct NewUser {
        var id: UUID?
        var username: String
    
        static let example = NewUser(id: nil, username: "")
    }
    

    and declare user

    @Published var user = NewUser.example