Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
144: MVVM in Swift Applications
Why do I even need a ViewModel? Can't I just put the logic in the View?
I get this question a lot, especially since SwiftUI makes it so easy to throw a few functions right inside your View struct. Sure, it works for a tiny prototype. But as soon as your app grows, you'll hit a wall. If you put your formatting logic, API calls, and state management inside the View, you end up with a "Massive View" that is nearly impossible to test without spinning up the entire UI simulator.
Think of the ViewModel as a translator. Your Model might give you a raw temperature in Kelvin from an API, but your View needs a formatted string like "72°F". If you put that conversion logic in the View, you can't test it in a unit test. If you put it in the ViewModel, you can write a simple test that says: "Given 295.15K, does the ViewModel return '72°F'?"
Here is a quick look at the difference using a weather app example:
// The Model: Pure data
struct Weather {
let temperatureKelvin: Double
let condition: String
}
// The ViewModel: The "brains" and translator
class WeatherViewModel: ObservableObject {
@Published var temperatureText: String = ""
@Published var conditionText: String = ""
func updateWeather(with weather: Weather) {
// Logic lives here, away from the UI
let celsius = weather.temperatureKelvin - 273.15
self.temperatureText = String(format: "%.0f°C", celsius)
self.conditionText = weather.condition.capitalized
}
}
// The View: Just displays what it's told
struct WeatherView: View {
@StateObject var viewModel = WeatherViewModel()
var body: some View {
VStack {
Text(viewModel.temperatureText)
.font(.largeTitle)
Text(viewModel.conditionText)
}
}
}
How does the View actually "stay in sync" with the ViewModel?
In the old days of UIKit, we had to use delegates or notifications, which felt like wiring a house by hand. In modern Swift, we use the ObservableObject protocol and the @Published property wrapper.
When you mark a property as @Published, Swift automatically creates a publisher. When that value changes, the ViewModel screams, "Hey, I've changed!" and any View observing that ViewModel via @StateObject or @ObservedObject automatically triggers a re-render of its body. It's a reactive loop. I highly recommend sticking to @StateObject when the View is the one creating the ViewModel, and @ObservedObject when the ViewModel is being passed in from a parent.
Where exactly does the network call go? In the Model or the ViewModel?
This is where people usually get tripped up. The ViewModel shouldn't actually *perform* the network request—it should *trigger* it. If you put the URLSession code directly inside your ViewModel, you've just made your ViewModel hard to test because it's now tied to the internet.
The best practice is to introduce a "Service" or "Repository" layer. The ViewModel asks the Service for data, the Service fetches it and returns a Model, and the ViewModel then transforms that Model into something the View can display. It adds one more file to your project, but trust me, it makes your architecture much cleaner.
class WeatherService {
func fetchWeather() async throws -> Weather {
// Actual URLSession logic goes here
return Weather(temperatureKelvin: 295.15, condition: "sunny")
}
}
class WeatherViewModel: ObservableObject {
@Published var temperatureText = "--"
private let service = WeatherService() // The VM depends on the service
func loadWeather() async {
do {
let weather = try await service.fetchWeather()
// Update UI on the main thread
await MainActor.run {
self.temperatureText = "\(Int(weather.temperatureKelvin - 273.15))°C"
}
} catch {
// Handle error
}
}
}
📋 Practical Task
Exercise: Building a User Profile Dashboard with MVVM
Your task is to move a messy "User Profile" implementation into a proper MVVM architecture. Currently, the View is handling data fetching and string formatting, which makes it bloated.
- The Model: Create a
Userstruct withfirstName,lastName, andjoinDate(as aDateobject). - The ViewModel: Create a
UserProfileViewModelthat:- Holds a
Usermodel. - Exposes a
fullNamestring (combining first and last names). - Exposes a
memberSincestring (formatting theDateinto a readable string like "Joined: January 2023"). - Includes a function
refreshUser()that simulates a network delay usingTask.sleepbefore updating the user data.
- Holds a
- The View: Create a
UserProfileViewthat displays thefullNameandmemberSincetext. Add a button that callsrefreshUser(). Ensure the View does not contain any logic for combining names or formatting dates.
There are no comments for now.