struct ProfileEditView: View {
@ObservedObject var viewModel: UsersViewModel
@StateObject var auth: Authenticator
@State var showingImageEditor: Bool = false
init(_ viewModel: UsersViewModel, _ auth: Authenticator) {
self.viewModel = viewModel
self.auth = auth
UITableView.appearance().backgroundColor = UIColor.clear
UITableViewCell.appearance().selectionStyle = .none
}
var body: some View { }
}
I am trying to manually intialize a view that takes a StateObject
as a parameter. I am getting an error: Cannot assign to property: 'auth' is a get-only property
. What is the proper way to write the initializer?
2
Answers
I can’t fully reproduce your code without your definitions of
Authenticator
andUsersViewModel
, but I got it to compile:These are the key changes:
If you don’t understand my changes you should google
to get a better understanding of what property wrappers are and how to use them.
In addition to the ‘accepted answer’ there’s a really good example that will allow everyone to reproduce the error and understand how to avoid it.
Considering there’s a
viewModel
in aView
with a property wrapper@StateObject
, there’s no need to initiate aStateObject(wrappedValue: ...)
in the constructor as long as there are no private properties in theView
. Let’s see an example:The above example will work by simply using:
But if we will add a private property to the
View
:Our previous example
MyView(viewModel: MyViewModel())
will now produce the following error:So please consider why you declare a property in a
View
private, perhaps it can be moved to theViewModel
and the issue will be solved in order to utilize the dependency injection principle.