show me an example of mvvm in swift

Here's an example of MVVM architecture in Swift:

Model - User.swift

main.swift
struct User {
    var name: String
    var email: String
}
59 chars
5 lines

View - UserProfileViewController.swift

main.swift
import UIKit

class UserProfileViewController: UIViewController {
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    
    var viewModel: UserProfileViewModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        bindViewModel()
    }
    
    private func bindViewModel() {
        viewModel = UserProfileViewModel()
        
        viewModel.nameText.bind(to: nameLabel.rx.text).disposed(by: disposeBag)
        viewModel.emailText.bind(to: emailLabel.rx.text).disposed(by: disposeBag)
    }
}
567 chars
22 lines

ViewModel - UserProfileViewModel.swift

main.swift
import Foundation
import RxSwift
import RxCocoa

class UserProfileViewModel {
    var user: User

    var nameText = BehaviorSubject<String>(value: "")
    var emailText = BehaviorSubject<String>(value: "")

    init() {
        user = User(name: "John Doe", email: "johndoe@example.com")
        setup()
    }
    
    func setup() {
        nameText.onNext(user.name)
        emailText.onNext(user.email)
    }
}
415 chars
21 lines

In summary, the View is responsible for displaying data and user interaction, the ViewModel is responsible for preparing data for presentation and responding to user interaction, and the Model is responsible for representing the data.

related categories

gistlibby LogSnag