how to create a view model in swift

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).

  1. Define your model:

    main.swift
    struct Person: Codable {
        let name: String
        let age: Int
    }
    
    65 chars
    5 lines
  2. Create a view model:

    main.swift
    import Foundation
    
    class PersonViewModel {
        var person: Person
    
        init(person: Person) {
            self.person = person
        }
    
        var name: String {
            return person.name
        }
    
        var age: Int {
            return person.age
        }
    }
    
    240 chars
    18 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.swift
class ViewController: UIViewController {

    var viewModel: PersonViewModel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Initialize view model with a Person object
        let person = Person(name: "John", age: 25)
        viewModel = PersonViewModel(person: person)

        // Update UI with view model properties
        nameLabel.text = viewModel.name
        ageLabel.text = "\(viewModel.age)"
    }
}
439 chars
17 lines

This way, your view controller does not interact directly with your model and your data management is abstracted in your ViewModel.

gistlibby LogSnag