In my pursuit to learn SwiftUI, I am really struggling with this MVVM architecture. With that being said, I have a project which I have been working on to learn this. With some help of other folks I have gotten this far.
The current issue is, I need to make the @Published
property wrapped on the View Model to have optional parameters. Unfortunately, everything I try is not working. What I am looking to do is take what the user inputs on the TextFields and use them in math functions.
Model.swift
// Model.
protocol Height {
var heightInCentimeters: Int { get }
}
struct ImperialHeight: Height {
var feet: Int
var inches: Int
var heightInCentimeters: Int {
Int(((Double(feet) * 12.0)) + Double(inches) * 2.54)
}
}
struct MetricHeight: Height {
var heightInCentimeters: Int
}
protocol Weight {
var weightInKilograms: Int { get }
}
struct ImperialWeight: Weight {
var pounds: Int
var weightInKilograms: Int {
Int(Double(pounds) * 0.4535924)
}
}
struct MetricWeight {
var weightInKilograms: Int
}
struct UserData {
var age: Int = 18
var weight: Weight
var height: Height
}
View Model
class UserDataViewModel: ObservableObject {
@Published var userData: UserData = UserData(weight: ImperialWeight(pounds: 220), height: ImperialHeight(feet: 6, inches: 2))
...
As stated above, the current issue is that the @Published
property wrapper requires the weight and height. Ideally I would like to make those optionals which populates that data via users TextField input.
I've tried reading numerous documentations, tutorials and guides. Unfortunately I'm failing to grasp the concept still in terms of how to apply it with my project.
I think you are over complicating it a little. You can use
Measurement
to do most of the work for you. If you want to have different ways editing a measurement just have a single source of truth. Below is an example withheight
And this code can be for any length. Not just height.