{"id":2612,"date":"2026-02-05T07:33:30","date_gmt":"2026-02-05T07:33:30","guid":{"rendered":"https:\/\/demo.materiamedica.net\/demo6\/?p=2612"},"modified":"2026-02-05T07:33:30","modified_gmt":"2026-02-05T07:33:30","slug":"chapter-15-real-life-examples","status":"publish","type":"post","link":"https:\/\/demo.materiamedica.net\/demo6\/chapter-15-real-life-examples\/","title":{"rendered":"Chapter 15: Real-Life Examples"},"content":{"rendered":"<p dir=\"auto\"><strong>Real-life examples<\/strong> of Swift code.<\/p>\n<p dir=\"auto\">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.<\/p>\n<p dir=\"auto\">We will look at different common scenarios step by step.<\/p>\n<h3 dir=\"auto\">1. User Profile \u2013 very common in almost every app<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>struct UserProfile {\r\n    \/\/ These never change after creation \u2192 use let\r\n    let userID: UUID\r\n    let createdAt: Date\r\n    let email: String\r\n    \r\n    \/\/ These can be changed by the user\r\n    var displayName: String\r\n    var profilePhotoURL: URL?\r\n    var bio: String?\r\n    var isPremium: Bool\r\n    \r\n    \/\/ Example of a computed property (read-only)\r\n    var shortName: String {\r\n        let parts = displayName.split(separator: \" \")\r\n        if parts.count &gt;= 2 {\r\n            return \"\\(parts[0]) \\(String(parts[1].prefix(1))).\"\r\n        }\r\n        return displayName\r\n    }\r\n    \r\n    \/\/ Initialization with default values\r\n    init(\r\n        userID: UUID = UUID(),\r\n        createdAt: Date = Date(),\r\n        email: String,\r\n        displayName: String,\r\n        profilePhotoURL: URL? = nil,\r\n        bio: String? = nil,\r\n        isPremium: Bool = false\r\n    ) {\r\n        self.userID = userID\r\n        self.createdAt = createdAt\r\n        self.email = email\r\n        self.displayName = displayName\r\n        self.profilePhotoURL = profilePhotoURL\r\n        self.bio = bio\r\n        self.isPremium = isPremium\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real-life usage:<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>let currentUser = UserProfile(\r\n    email: \"aarav@example.com\",\r\n    displayName: \"Aarav Sharma\",\r\n    bio: \"I love coding in Swift and drinking chai \u2615\"\r\n)\r\n\r\n\/\/ Later when user edits profile\r\nvar updatedUser = currentUser\r\nupdatedUser.displayName = \"Aarav S.\"\r\nupdatedUser.bio = \"Swift developer | Hyderabad\"<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>What developers care about here:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>let for identity fields (userID, email, createdAt)<\/li>\n<li>var for editable fields<\/li>\n<li>Clean initialization<\/li>\n<li>Helpful computed properties<\/li>\n<\/ul>\n<h3 dir=\"auto\">2. Settings \/ Configuration \u2013 very common pattern<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>enum AppSettings {\r\n    static let appName = \"TaskMaster\"\r\n    static let version = \"2.1.4\"\r\n    static let supportEmail = \"help@taskmaster.app\"\r\n    \r\n    static let maxFreeProjects = 3\r\n    static let premiumMonthlyPrice: Decimal = 4.99\r\n    static let premiumYearlyPrice: Decimal = 49.99\r\n    \r\n    static let defaultTaskReminderMinutesBefore = 30\r\n    \r\n    static let apiBaseURL = URL(string: \"https:\/\/api.taskmaster.app\/v2\")!\r\n    static let timeoutInterval: TimeInterval = 30\r\n}\r\n\r\nenum Design {\r\n    static let cornerRadius: CGFloat = 12\r\n    static let smallSpacing: CGFloat = 8\r\n    static let standardMargin: CGFloat = 16\r\n    static let largeMargin: CGFloat = 24\r\n    static let buttonHeight: CGFloat = 48\r\n    static let preferredAnimationDuration = 0.3\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Real usage:<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>print(\"Welcome to \\(AppSettings.appName) v\\(AppSettings.version)\")\r\nprint(\"Need help? Contact \\(AppSettings.supportEmail)\")\r\n\r\nlet padding = Design.standardMargin<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Why this style?<\/strong><\/p>\n<ul dir=\"auto\">\n<li>Grouped constants<\/li>\n<li>No accidental changes (static + let)<\/li>\n<li>Easy to find and update values<\/li>\n<li>Clear separation between functional &amp; visual constants<\/li>\n<\/ul>\n<h3 dir=\"auto\">3. Loading data from API \u2013 very common async pattern<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>struct TodoItem: Codable, Identifiable {\r\n    let id: UUID\r\n    var title: String\r\n    var isCompleted: Bool\r\n    let createdAt: Date\r\n    var dueDate: Date?\r\n    \r\n    var isOverdue: Bool {\r\n        guard let dueDate else { return false }\r\n        return dueDate &lt; Date() &amp;&amp; !isCompleted\r\n    }\r\n}\r\n\r\n@MainActor\r\nclass TodoViewModel: ObservableObject {\r\n    @Published var todos: [TodoItem] = []\r\n    @Published var isLoading = false\r\n    @Published var errorMessage: String?\r\n    \r\n    func loadTodos() async {\r\n        isLoading = true\r\n        errorMessage = nil\r\n        \r\n        do {\r\n            let url = AppSettings.apiBaseURL.appending(path: \"todos\")\r\n            let (data, _) = try await URLSession.shared.data(from: url)\r\n            \r\n            let decoder = JSONDecoder()\r\n            decoder.dateDecodingStrategy = .iso8601\r\n            \r\n            todos = try decoder.decode([TodoItem].self, from: data)\r\n        } catch {\r\n            errorMessage = \"Failed to load tasks: \\(error.localizedDescription)\"\r\n        }\r\n        \r\n        isLoading = false\r\n    }\r\n    \r\n    func toggleCompletion(for todo: TodoItem) {\r\n        if let index = todos.firstIndex(where: { $0.id == todo.id }) {\r\n            todos[index].isCompleted.toggle()\r\n            \/\/ In real app: also send update to server\r\n        }\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Key observations:<\/strong><\/p>\n<ul dir=\"auto\">\n<li>let for unchanging data from server (id, createdAt)<\/li>\n<li>var for things user can change (isCompleted, title, dueDate)<\/li>\n<li>Clear separation between model and view model<\/li>\n<li>Safe async\/await pattern<\/li>\n<\/ul>\n<h3 dir=\"auto\">4. Simple form validation \u2013 very common in apps<\/h3>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>struct RegistrationForm {\r\n    var fullName = \"\"\r\n    var email = \"\"\r\n    var password = \"\"\r\n    var confirmPassword = \"\"\r\n    \r\n    var isValid: Bool {\r\n        !fullName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &amp;&amp;\r\n        email.contains(\"@\") &amp;&amp;\r\n        email.contains(\".\") &amp;&amp;\r\n        password.count &gt;= 8 &amp;&amp;\r\n        password == confirmPassword\r\n    }\r\n    \r\n    var validationMessages: [String] {\r\n        var messages: [String] = []\r\n        \r\n        if fullName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {\r\n            messages.append(\"Please enter your full name\")\r\n        }\r\n        \r\n        if !email.contains(\"@\") || !email.contains(\".\") {\r\n            messages.append(\"Please enter a valid email address\")\r\n        }\r\n        \r\n        if password.count &lt; 8 {\r\n            messages.append(\"Password must be at least 8 characters\")\r\n        }\r\n        \r\n        if password != confirmPassword {\r\n            messages.append(\"Passwords do not match\")\r\n        }\r\n        \r\n        return messages\r\n    }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\"><strong>Usage example:<\/strong><\/p>\n<div dir=\"auto\">\n<div data-testid=\"code-block\">\n<div>\n<div>Swift<\/div>\n<div>\n<pre tabindex=\"0\"><code>var form = RegistrationForm()\r\n\r\nform.fullName = \"Sneha Reddy\"\r\nform.email = \"sneha@example.com\"\r\nform.password = \"Secure123!\"\r\nform.confirmPassword = \"Secure123!\"\r\n\r\nif form.isValid {\r\n    print(\"Form is valid \u2013 can register\")\r\n} else {\r\n    print(\"Errors:\")\r\n    form.validationMessages.forEach { print(\"\u2022 \\($0)\") }\r\n}<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h3 dir=\"auto\">5. Quick summary \u2013 patterns we saw<\/h3>\n<div>\n<div dir=\"auto\">\n<table dir=\"auto\">\n<thead>\n<tr>\n<th data-col-size=\"md\">Situation<\/th>\n<th data-col-size=\"sm\">Common choices<\/th>\n<th data-col-size=\"lg\">Why?<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td data-col-size=\"md\">Identity \/ creation data<\/td>\n<td data-col-size=\"sm\">let<\/td>\n<td data-col-size=\"lg\">Never changes, part of object identity<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">User-editable fields<\/td>\n<td data-col-size=\"sm\">var<\/td>\n<td data-col-size=\"lg\">Must be able to change<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">App-wide fixed values<\/td>\n<td data-col-size=\"sm\">static let inside enum or struct<\/td>\n<td data-col-size=\"lg\">Organized, immutable, easy to find<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">UI \/ design values<\/td>\n<td data-col-size=\"sm\">static let in Design or Theme<\/td>\n<td data-col-size=\"lg\">Single source of truth for spacing, colors\u2026<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">Server response fields<\/td>\n<td data-col-size=\"sm\">let whenever possible<\/td>\n<td data-col-size=\"lg\">Data should not be accidentally modified<\/td>\n<\/tr>\n<tr>\n<td data-col-size=\"md\">State \/ loading flags<\/td>\n<td data-col-size=\"sm\">@Published var<\/td>\n<td data-col-size=\"lg\">View needs to react when they change<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<div><\/div>\n<\/div>\n<\/div>\n<p dir=\"auto\">Which of these real-life situations would you like to explore more deeply?<\/p>\n<ul dir=\"auto\">\n<li>More detailed <strong>API \/ networking<\/strong> example<\/li>\n<li><strong>SwiftUI view<\/strong> with real state management<\/li>\n<li><strong>Shopping cart \/ order<\/strong> example<\/li>\n<li><strong>Settings screen<\/strong> with persistence<\/li>\n<li><strong>Error handling<\/strong> in real apps<\/li>\n<li>Or any other scenario you meet often<\/li>\n<\/ul>\n<p dir=\"auto\">Just tell me what feels most useful right now \ud83d\ude0a<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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,&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[],"class_list":["post-2612","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2612","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/comments?post=2612"}],"version-history":[{"count":1,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2612\/revisions"}],"predecessor-version":[{"id":2613,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/posts\/2612\/revisions\/2613"}],"wp:attachment":[{"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/media?parent=2612"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/categories?post=2612"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/demo.materiamedica.net\/demo6\/wp-json\/wp\/v2\/tags?post=2612"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}