I've just begun building what will be a pretty extensive application and want to use MVVM to organize things as it scales up. I'm having a lot of trouble understanding how to correctly bridge between a Model
and a ViewModel
.
I have the main "user account" Model
like this:
struct UserSLP: Codable, Hashable {
let email : String
let password : String
let firstName : String
let lastName : String
let state : String
let zipCode : String
let company : String
let licenseNumber : String
let licenseState : String
let phoneNumber : String
let timezone : String
let language : String
let token: String
}
In my ViewModel
, I have the same variables created which my View
then pushes form data into:
class slpCreateAccount: ObservableObject {
var slpEmail: String = ""
var slpPassword: String = ""
var slpFirstName: String = ""
var slpLastName: String = ""
var slpZipCode: String = ""
@Published var slpStateSelection: String = "State"
var slpCompany: String = ""
var slpLicenseNumber: String = ""
@Published var slpLicenseState: String = "License State"
var slpPhoneNumber: String = ""
@Published var slpTimezone: String = "Timezone"
@Published var slpLanguage: String = "Language"
}
In my ViewModel
, I also have a network call to the server and database to create this user's account. PS - I publish those 4 variables above because they're Pickers()
in the View's Form and need the default string values(state, license state, etc.) displayed there before users pick something. Maybe that's the wrong way? Anyways, here's an example of one of the form field pickers in the View
.
HStack {
Image(systemName: "location")
.font(.system(size: 37, weight: .ultraLight))
Picker(selection: $slpCreateAccountVM.slpStateSelection,
label: Text(slpCreateAccountVM.slpStateSelection),
content: {
ForEach(StatesList().states.sorted{ $0 > $1 }, id: \.self) { states in
Text(states)
}
})
.pickerStyle(MenuPickerStyle())
.frame(width: 300, alignment: .leading)
.padding()
.background(Color(#colorLiteral(red: 0.9545406699, green: 0.9489219785, blue: 0.9588606954, alpha: 1)))
.cornerRadius(10)
.foregroundColor(.black)
}
.padding(.bottom, 10)
So I push my View
form data into the ViewModel
variables, but I'm also supposed to use the Model
Struct UserSLP as some sort of blueprint for handling that data as well?
I just want to follow the correct approach here, get the user's inputs on their form into the ViewModel
and into my network call. The network call piece is working great with hard-coded parameters. Just need to figure out how exactly a ViewModel
and Model
work together here.
Thanks in advance and sorry for the long post.