Проектирование ViewModel
Создайте модель представления экрана с @Observable.
«Проектирование ViewModel» — бесплатный урок SwiftUI Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения SwiftUI Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс SwiftUI Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
A ViewModel Is Just a Class
A ViewModel is usually a class that holds the state and logic for one screen. Using a class lets several views share the same live instance.
class ProfileViewModel {
var name: String = ""
}Make It Observable
Add the @Observable macro so SwiftUI tracks property changes and re-renders the view automatically when state updates.
@Observable
class ProfileViewModel {
var name = ""
}Expose View-Ready State
Give the ViewModel properties the view can read directly, like a formatted greeting, so the view never does its own string building.
var greeting: String {
"Hi, " + name
}Hold the Loading Flag
Track UI status inside the ViewModel. A simple isLoading boolean lets the view decide when to show a spinner versus content.
var isLoading = falseKeep Intent in Methods
Expose actions as methods like load() or save(). The view calls them on tap; the ViewModel decides exactly what happens.
func load() {
isLoading = true
}Name Properties for the UI
Name state after what the screen shows, like buttonTitle or rows, not after raw data. This keeps the view almost declarative.
Hide the Messy Details
Parsing, math, and edge cases belong inside the ViewModel. The view should see clean values and never touch the rough work.
One ViewModel per Screen
Give each screen its own focused ViewModel. A small, single-purpose model is far easier to read, reason about, and test.
Start Empty, Then Fill
Initialize the ViewModel with sensible empty defaults, then populate it when data arrives. The view shows a calm empty state meanwhile.
Avoid View Code Inside
Never import view types or layout code into a ViewModel. Keeping it UI-free is what makes it portable and easy to unit test. ✨
A Complete Small Example
This tiny ViewModel exposes a count and a method to change it, giving the view everything it needs in two clear members.
@Observable
class CounterViewModel {
var count = 0
func increment() { count += 1 }
}Quick Check
Which macro makes a ViewModel class trigger SwiftUI updates?
Recap: Designing a ViewModel
You built an @Observable class that exposes view-ready state and intent methods while hiding the messy details. Next you will bind views to it.
Часто задаваемые вопросы
Урок «Проектирование ViewModel» бесплатный?
Да — полный текст урока «Проектирование ViewModel» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс SwiftUI Academy, подпишись на CoddyKit PRO. Курс SwiftUI Academy содержит 4 уроков всего.
Чему я научусь в уроке «Проектирование ViewModel»?
Создайте модель представления экрана с @Observable. Ты практикуешь SwiftUI Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать SwiftUI Academy?
Предыдущий опыт не требуется. SwiftUI Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Проектирование ViewModel»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке SwiftUI Academy?
Да. Каждый урок SwiftUI Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Почему MVVM подходит для SwiftUI
- Проектирование ViewModel
- Связывание представлений с ViewModels
- Внедрение зависимостей для ViewModels