0

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

1 Answers1

1

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
vadian
  • 274,689
  • 30
  • 353
  • 361