Chapter 15: Real-Life Examples
Real-life examples of Swift code.
I will show you many practical, realistic situations where Swift is actually used, explain what each piece of code is trying to do, why it is written this way, and what real developers care about in these situations.
We will look at different common scenarios step by step.
1. User Profile – very common in almost every app
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
struct UserProfile { // These never change after creation → use let let userID: UUID let createdAt: Date let email: String // These can be changed by the user var displayName: String var profilePhotoURL: URL? var bio: String? var isPremium: Bool // Example of a computed property (read-only) var shortName: String { let parts = displayName.split(separator: " ") if parts.count >= 2 { return "\(parts[0]) \(String(parts[1].prefix(1)))." } return displayName } // Initialization with default values init( userID: UUID = UUID(), createdAt: Date = Date(), email: String, displayName: String, profilePhotoURL: URL? = nil, bio: String? = nil, isPremium: Bool = false ) { self.userID = userID self.createdAt = createdAt self.email = email self.displayName = displayName self.profilePhotoURL = profilePhotoURL self.bio = bio self.isPremium = isPremium } } |
Real-life usage:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let currentUser = UserProfile( email: "aarav@example.com", displayName: "Aarav Sharma", bio: "I love coding in Swift and drinking chai ☕" ) // Later when user edits profile var updatedUser = currentUser updatedUser.displayName = "Aarav S." updatedUser.bio = "Swift developer | Hyderabad" |
What developers care about here:
- let for identity fields (userID, email, createdAt)
- var for editable fields
- Clean initialization
- Helpful computed properties
2. Settings / Configuration – very common pattern
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
enum AppSettings { static let appName = "TaskMaster" static let version = "2.1.4" static let supportEmail = "help@taskmaster.app" static let maxFreeProjects = 3 static let premiumMonthlyPrice: Decimal = 4.99 static let premiumYearlyPrice: Decimal = 49.99 static let defaultTaskReminderMinutesBefore = 30 static let apiBaseURL = URL(string: "https://api.taskmaster.app/v2")! static let timeoutInterval: TimeInterval = 30 } enum Design { static let cornerRadius: CGFloat = 12 static let smallSpacing: CGFloat = 8 static let standardMargin: CGFloat = 16 static let largeMargin: CGFloat = 24 static let buttonHeight: CGFloat = 48 static let preferredAnimationDuration = 0.3 } |
Real usage:
|
0 1 2 3 4 5 6 7 8 9 |
print("Welcome to \(AppSettings.appName) v\(AppSettings.version)") print("Need help? Contact \(AppSettings.supportEmail)") let padding = Design.standardMargin |
Why this style?
- Grouped constants
- No accidental changes (static + let)
- Easy to find and update values
- Clear separation between functional & visual constants
3. Loading data from API – very common async pattern
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
struct TodoItem: Codable, Identifiable { let id: UUID var title: String var isCompleted: Bool let createdAt: Date var dueDate: Date? var isOverdue: Bool { guard let dueDate else { return false } return dueDate < Date() && !isCompleted } } @MainActor class TodoViewModel: ObservableObject { @Published var todos: [TodoItem] = [] @Published var isLoading = false @Published var errorMessage: String? func loadTodos() async { isLoading = true errorMessage = nil do { let url = AppSettings.apiBaseURL.appending(path: "todos") let (data, _) = try await URLSession.shared.data(from: url) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 todos = try decoder.decode([TodoItem].self, from: data) } catch { errorMessage = "Failed to load tasks: \(error.localizedDescription)" } isLoading = false } func toggleCompletion(for todo: TodoItem) { if let index = todos.firstIndex(where: { $0.id == todo.id }) { todos[index].isCompleted.toggle() // In real app: also send update to server } } } |
Key observations:
- let for unchanging data from server (id, createdAt)
- var for things user can change (isCompleted, title, dueDate)
- Clear separation between model and view model
- Safe async/await pattern
4. Simple form validation – very common in apps
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
struct RegistrationForm { var fullName = "" var email = "" var password = "" var confirmPassword = "" var isValid: Bool { !fullName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && email.contains("@") && email.contains(".") && password.count >= 8 && password == confirmPassword } var validationMessages: [String] { var messages: [String] = [] if fullName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { messages.append("Please enter your full name") } if !email.contains("@") || !email.contains(".") { messages.append("Please enter a valid email address") } if password.count < 8 { messages.append("Password must be at least 8 characters") } if password != confirmPassword { messages.append("Passwords do not match") } return messages } } |
Usage example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var form = RegistrationForm() form.fullName = "Sneha Reddy" form.email = "sneha@example.com" form.password = "Secure123!" form.confirmPassword = "Secure123!" if form.isValid { print("Form is valid – can register") } else { print("Errors:") form.validationMessages.forEach { print("• \($0)") } } |
5. Quick summary – patterns we saw
| Situation | Common choices | Why? |
|---|---|---|
| Identity / creation data | let | Never changes, part of object identity |
| User-editable fields | var | Must be able to change |
| App-wide fixed values | static let inside enum or struct | Organized, immutable, easy to find |
| UI / design values | static let in Design or Theme | Single source of truth for spacing, colors… |
| Server response fields | let whenever possible | Data should not be accidentally modified |
| State / loading flags | @Published var | View needs to react when they change |
Which of these real-life situations would you like to explore more deeply?
- More detailed API / networking example
- SwiftUI view with real state management
- Shopping cart / order example
- Settings screen with persistence
- Error handling in real apps
- Or any other scenario you meet often
Just tell me what feels most useful right now 😊
