To create a view model in Swift, you can follow the MVVM (Model-View-ViewModel) architecture. A view model acts as a mediator between the view (UI) and the model (data).
Define your model:
main.swift65 chars5 lines
Create a view model:
main.swift240 chars18 lines
In this example, the view model PersonViewModel
takes a Person
model as a parameter and exposes its properties to the view.
By using the Codable protocol, you can easily map the response from an API to your model class.
This allows you to manage your data and logic separately from your view, which follows the Separation of Concerns principle.
Here's an example of how you can use this view model in a view controller:
main.swift439 chars17 lines
This way, your view controller does not interact directly with your model and your data management is abstracted in your ViewModel.
gistlibby LogSnag