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.
struct NewUser: {
var id: UUID?
var username: String
}
class HTTPUserClient: ObservableObject {
@Published var user: NewUser? //a user struct with a non optional
//function and stuff ommitted
}
import SwiftUI
struct TestUserEditor: View {
@ObservedObject var userClient:HTTPUserClient
var body: some View {
TextField("required", text: $userClient.user!.username)
}
}
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
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