Junior — Middle
Can you explain what is meant by ViewModel in application architecture?
sobes.tech AI
Answer from AI
ViewModel is a component of the MVVM (Model-View-ViewModel) architecture that acts as an intermediary between the data model and the user interface (View). Its task is to store and process data necessary for display, as well as to manage presentation logic that is independent of the UI.
In iOS, ViewModel helps separate business logic from UI code, simplifying testing and maintenance. For example, a ViewModel can fetch data from the network or database, format it, and provide it ready for display in the View.
A simple example of a ViewModel in Swift:
class UserViewModel {
private let user: User
var displayName: String {
return "Name: \(user.firstName) \(user.lastName)"
}
init(user: User) {
self.user = user
}
}
Here, the ViewModel provides the View with a convenient data format, hiding the details of the model.