<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rajesh Mani on Medium]]></title>
        <description><![CDATA[Stories by Rajesh Mani on Medium]]></description>
        <link>https://medium.com/@iosdevrajesh?source=rss-bff1c5fe0850------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D8dDRAw_wCdrkjnnm-HGRQ.jpeg</url>
            <title>Stories by Rajesh Mani on Medium</title>
            <link>https://medium.com/@iosdevrajesh?source=rss-bff1c5fe0850------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:55:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iosdevrajesh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[One Language to Rule the Stack: Building an Enterprise-Grade Full-Stack App with Swift 6, Vapor 4…]]></title>
            <link>https://medium.com/@iosdevrajesh/one-language-to-rule-the-stack-building-an-enterprise-grade-full-stack-app-with-swift-6-vapor-4-c36685245f65?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36685245f65</guid>
            <category><![CDATA[swift-fullstack]]></category>
            <category><![CDATA[swift-server-side-api]]></category>
            <category><![CDATA[vaporswift]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 19:41:01 GMT</pubDate>
            <atom:updated>2026-09-15T19:41:01.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>One Language to Rule the Stack: Building an Enterprise-Grade Full-Stack App with Swift 6, Vapor 4, and SwiftUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbmFqqw6Jsf8WlVpgB_X1g.jpeg" /></figure><p><em>How unifying mobile clients and backend infrastructure under Swift 6 delivers unmatched type safety, sub-millisecond concurrency, and extreme developer velocity.</em></p><h3>1. Introduction: The Full-Stack Swift Paradigm</h3><p>For years, iOS developers lived in a divided world: we crafted pixel-perfect UI and rock-solid state management in Swift on the client, only to switch context to Node.js, Go, or Python the moment we needed a backend service.</p><p>While polyglot architectures have their place, context switching introduces friction: duplicate model definitions, subtle serialization mismatches, divergent validation rules, and disparate tooling.</p><p>With the maturation of <strong>Swift 6</strong> and <strong>Vapor 4</strong>, the vision of <strong>Full-Stack Swift</strong> is no longer an experimental hobby — it is an enterprise-ready reality.</p><p>In this deep dive, we break down the architecture of <strong>SchoolBee / StudyApp</strong>, an end-to-end academic lifecycle management ecosystem powered by:</p><ul><li><strong>Client</strong>: Native iOS application built with <strong>SwiftUI</strong></li><li><strong>Server</strong>: High-throughput backend powered by <strong>Vapor 4</strong> and <strong>Swift 6</strong></li><li><strong>Persistence</strong>: <strong>PostgreSQL 16</strong> via the <strong>Fluent ORM</strong></li><li><strong>APIs</strong>: Dual <strong>REST</strong> and <strong>GraphQL</strong> gateways with interactive GraphiQL tooling</li><li><strong>DevOps</strong>: Multi-stage Linux Docker containers, GHCR automated pipelines, and automated database migrations</li></ul><h3>2. System Architecture: From Pixel to Postgres</h3><p>The entire platform is engineered around end-to-end type safety, structured concurrency, and defensive security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*lRM3LcbEhd-BEQuvbiKo4Q.png" /></figure><h3>3. Why Swift on the Server? The Engineering Advantages</h3><h3>1. Unified Domain Models &amp; Elimination of Impedance Mismatch</h3><p>In traditional stacks, an iOS DTO and a backend response schema drift apart easily. In Full-Stack Swift, data contracts can be shared directly:</p><ul><li>Shared validation routines (e.g., email format, password entropy)</li><li>Guaranteed serialization parity with Codable</li><li>Compile-time verification across client and server boundaries</li></ul><h3>2. Swift 6 Concurrency &amp; Complete Data Race Safety</h3><p>Swift 6 enforces compile-time verification of data race safety. By embracing:</p><ul><li>Strongly typed actors</li><li>Sendable protocol guarantees across asynchronous boundaries</li><li>Structured concurrency with async/await and task groups</li></ul><p>Our backend services process thousands of simultaneous connections without risk of race conditions or data corruption — all without the CPU overhead of thread thrashing.</p><h3>3. Minimal Memory Footprint &amp; Instant Cold Starts</h3><p>Unlike JVM runtimes that require gigabytes of heap memory or Node.js runtimes with bloated V8 runtimes, a compiled Swift Linux binary starts in <strong>under 10 milliseconds</strong> and typically runs on <strong>less than 30–50 MB of RAM</strong>. This makes horizontal scaling and container orchestration astonishingly cost-effective.</p><h3>4. Dual API Gateways: REST and GraphQL in Harmony</h3><p>Clients don’t all consume data the same way. Rather than forcing a single paradigm, the architecture exposes both <strong>REST</strong> and <strong>GraphQL</strong>:</p><h3>REST for Predictable CRUD &amp; Strict Workflows</h3><ul><li>Identity lifecycle: Registration, Login, Token Refresh</li><li>Password reset and email OTP verification</li><li>Deterministic HTTP status codes (201 Created, 401 Unauthorized, 409 Conflict, 429 Too Many Requests)</li></ul><h3>GraphQL for Flexible UI Aggregation</h3><ul><li>Integrated via <strong>Pioneer</strong> and <strong>GraphQL-Kit</strong></li><li>Allows the iOS SwiftUI client to request precisely the student profile attributes, courses, and assignment states needed for a specific view</li><li>Prevents over-fetching and under-fetching over cellular networks</li><li>Built-in GraphiQL interactive playground (/graphiql) for rapid developer exploration</li></ul><h3>5. Defense-in-Depth: Production Security Hardening</h3><p>Security is not an afterthought; it is built into every layer of the request pipeline:</p><p><strong>Defensive Middlewares</strong>:</p><ul><li>SecurityHeadersMiddleware: Enforces Strict-Transport-Security (HSTS), restrictive Content-Security-Policy (CSP), and X-Frame-Options: DENY.</li><li>RateLimiterMiddleware: In-memory IP and endpoint rate limiting protecting against brute-force password guessing and DDoS.</li><li>CORSMiddleware: Strict origin whitelisting.</li></ul><p><strong>Stateful Token Revocation</strong>:</p><p>Stateless JWTs are fast, but they make immediate revocation tricky.</p><ol><li>We implemented a hybrid strategy: tokens are cryptographically verified via JWT, but also checked against a high-speed revoked token registry for immediate session invalidation on logout or password change.</li></ol><p><strong>IDOR &amp; Role-Based Access Control (RBAC)</strong>:</p><ol><li>Deep parameter checking prevents Insecure Direct Object References (IDOR). A student token can never read or mutate another student’s academic record.</li></ol><h3>6. Cloud-Native DevOps &amp; Deployment</h3><p>A backend is only as good as its deployment pipeline:</p><ul><li><strong>Multi-Stage Docker Builds</strong>: Built on Ubuntu Noble, compiling the release binary in a builder stage and copying only the compiled executable and required dynamic libraries into a minimal distroless-like runtime image.</li><li><strong>Automated CI/CD</strong>: GitHub Actions matrix testing on Swift 6 and automated push to GitHub Container Registry (GHCR).</li><li><strong>Zero-Downtime Database Migrations</strong>: Fluent migration runbooks decoupled from app boot to ensure high-availability database schema evolutions.</li><li><strong>Production Reverse Proxy</strong>: Caddy container handling automated Let’s Encrypt TLS certificates, HTTP/2 multiplexing, and static asset serving.</li></ul><h3>7. Key Takeaways &amp; Lessons Learned</h3><ol><li><strong>Swift on Linux is genuinely production ready</strong>: Memory consumption is whisper-quiet, CPU utilization stays low, and stability is top tier.</li><li><strong>One Mental Model</strong>: Moving between client SwiftUI views and server Vapor controllers without switching languages drastically enhances developer flow state.</li><li><strong>Strict Concurrency Pays Off</strong>: Swift 6 compiler errors can be demanding at first, but once the code compiles, concurrency bugs are virtually nonexistent.</li></ol><h3>Connect &amp; Collaborate</h3><p>Have you experimented with Server-Side Swift or Vapor? How does your team approach full-stack type safety?</p><p>Let’s discuss in the comments below! 🚀 <a href="https://github.com/rajeshm20/StudentAppBackend.git">https://github.com/rajeshm20/StudentAppBackend.git</a></p><p><em>Built with Swift 6, Vapor 4, SwiftUI, and PostgreSQL.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36685245f65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing the API Surface: REST, GraphQL, and Route Registration — Part 3]]></title>
            <link>https://medium.com/@iosdevrajesh/designing-the-api-surface-rest-graphql-and-route-registration-320342265cb2?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/320342265cb2</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[swiftonserver]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[vaporswift]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 16:40:23 GMT</pubDate>
            <atom:updated>2026-07-20T16:41:36.194Z</atom:updated>
            <content:encoded><![CDATA[<p>Every endpoint in StudentAppBackend, documented one by one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92UjtM727-bXbayGXGtH0Q.jpeg" /></figure><p>This article documents every route and GraphQL operation in `StudentAppBackend`. It covers method, path, purpose, request shape, authentication requirements, responses, middleware, and error cases. It also explains why mixing REST and GraphQL in a small backend is both educational and architecturally revealing.</p><p>One of the fastest ways to evaluate a backend is to ignore the framework choice and just ask a harder question:</p><p>What is the actual API surface?</p><p>In `StudentAppBackend`, the answer is compact enough to enumerate completely, which is ideal for analysis. The app exposes:</p><p>- two REST endpoints under <em>/auth</em>,<br>- one GraphQL transport endpoint at <em>/graphql</em>,<br>- one GraphiQL UI endpoint at <em>/graphiql</em>,<br>- and five GraphQL operations inside the schema.</p><p>The route registration is deliberately small in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Routes/routes.swift">routes.swift</a></p><pre>func routes(_ app: Application) throws {<br> try app.register(collection: AuthController())<br> try registerGraphQLRoutes(app)<br>}</pre><p>That means the app’s public surface splits into two worlds:</p><p>- REST for signup and login,<br>- GraphQL for queries and mirrored mutations.</p><p>This is not inherently wrong. In fact, it is a useful experimental pattern because it lets the project compare two API styles over the same domain. But it does create duplication, and duplication is where architectural intent becomes visible.</p><p>Let’s document everything precisely.</p><p><strong>Global middleware that affects every route</strong></p><p>Before looking at handlers, remember that all public routes pass through:</p><p>1.<em> CORSMiddleware<br>2. SecurityHeadersMiddleware</em><br>3. <em>RateLimiterMiddleware</em></p><p>Registered in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift">configure.swift:45–47</a> and again in the default branch at <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift">configure.swift:99–101</a></p><p>No route-specific authentication middleware is attached anywhere in the codebase.</p><p>That means every route below is currently public unless the handler itself manually checks something. In practice, none of them do.</p><h3><strong>REST endpoints</strong></h3><p><strong><em>1. POST /auth/signup</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Controllers/AuthController.swift">AuthController.swift:21</a></p><p><strong>Purpose</strong><br>Create a student account.</p><p><strong>Request body<br></strong>Decoded from `Student.CreateRequest` in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Models/Student.swift">Student.swift:65</a></p><pre>{<br> &quot;name&quot;: &quot;Karthick&quot;,<br> &quot;email&quot;: &quot;karthickt@example.com&quot;,<br> &quot;password&quot;: &quot;secret123&quot;,<br> &quot;dob&quot;: &quot;1980–07–18T00:00:00Z&quot;,<br> &quot;phoneNumber&quot;: &quot;1234567890&quot;<br>}</pre><p><strong>Fields</strong>:</p><p>- <em>name: String</em><br>- <em>email: String</em><br>- <em>password: String</em><br>- <em>dob: Date?</em><br>- <em>phoneNumber: String?</em></p><p><strong>Authentication required</strong><br>No.</p><p><strong>Middleware involved</strong></p><p>- CORS<br>- Security headers<br>- Rate limiting: default rule `100 requests / 60 seconds` per IP and route path</p><p><strong>Handler behavior</strong></p><p>1. Decode JSON body.<br>2. Hash the password with `Bcrypt.hash`.<br>3. Create a `Student`.<br>4. Save to MySQL through Fluent.<br>5. Return `Student.Public`.</p><p><strong>Response shape</strong></p><p>Returns a public student object without `passwordHash`:</p><pre>{<br> &quot;id&quot;: &quot;UUID&quot;,<br> &quot;name&quot;: &quot;Karthick&quot;,<br> &quot;email&quot;: &quot;karthickt@example.com&quot;,<br> &quot;dob&quot;: &quot;1980–07–18T00:00:00Z&quot;,<br> &quot;phoneNumber&quot;: &quot;1234567890&quot;<br>}</pre><p><strong>Error cases</strong></p><p>- `400 Bad Request` if body decoding fails.<br>- Database error if the unique email constraint is violated.<br>- Unhandled persistence errors bubble through Vapor.</p><p><strong>Important tradeoff</strong><br>There is no validation layer before hashing or saving. Empty names, malformed emails, and weak passwords are not filtered in application code.</p><p><strong><em>2. `POST /auth/login`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Controllers/AuthController.swift">AuthController.swift:39</a></p><p><strong>Purpose</strong><br>Authenticate a student and return a JWT.</p><p><strong>Request body</strong><br>Decoded from `Student.LoginRequest` in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Models/Student.swift">Student.swift:57</a></p><pre>{<br> &quot;email&quot;: &quot;karthickt@example.com&quot;,<br> &quot;password&quot;: &quot;secret123&quot;<br>}</pre><p><strong>Authentication required</strong><br>No.</p><p><strong>Middleware involved</strong></p><p>- CORS<br>- Security headers<br>- Rate limiting: stricter rule `5 requests / 60 seconds` per IP for routes beginning with `/auth/login`</p><p><strong>Handler behavior</strong></p><p>1. Decode credentials.<br>2. Look up the student by email through `StudentService.authenticate`.<br>3. Verify password with `Bcrypt.verify`.<br>4. Build a `StudentToken`.<br>5. Sign JWT with `req.jwt.sign`.<br>6. Return user plus token.</p><p><strong>Response shape</strong></p><p>From `LoginResponse` in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Controllers/AuthController.swift">AuthController.swift:54</a></p><pre>{<br> &quot;user&quot;: {<br> &quot;id&quot;: &quot;UUID&quot;,<br> &quot;name&quot;: &quot;Karthick&quot;,<br> &quot;email&quot;: &quot;karthickt@example.com&quot;,<br> &quot;dob&quot;: null,<br> &quot;phoneNumber&quot;: null<br> },<br> &quot;token&quot;: {<br> &quot;token&quot;: &quot;jwt-string&quot;<br> },<br> &quot;status&quot;: &quot;ok&quot;<br>}</pre><p><strong>Error cases</strong></p><p>- `401 Unauthorized` for invalid email/password.<br>- `400 Bad Request` for decode failures.<br>- DB lookup failures bubble up.</p><p><strong>Important tradeoff</strong><br>The route issues a token, but there is no downstream protected REST endpoint that uses it.</p><h3><strong>Transport routes outside REST</strong></h3><p><strong><em>3. `POST /graphql`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Routes/graphqlRoutes.swift">graphqlRoutes.swift:8</a></p><p><strong>Purpose</strong><br>Accept GraphQL requests and execute them against `StudentGraphQLAPI`.</p><p><strong>Request body</strong><br>Decoded from `GraphQLRequestBody` in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swif">GraphQLAPI.swift:7</a></p><pre>{<br> &quot;query&quot;: &quot;{ students { id name email } }&quot;,<br> &quot;operationName&quot;: null,<br> &quot;variables&quot;: {}<br>}</pre><p><strong>Authentication required</strong><br>No.</p><p><strong>Middleware involved</strong></p><p>- CORS<br>- Security headers<br>- Rate limiting: default rule `100 requests / 60 seconds` per IP and route path `/graphql`</p><p><strong>Response shape</strong><br>Always HTTP `200 OK` if execution reaches GraphQL, even when the GraphQL payload contains errors. The body is JSON-encoded GraphQL result data.</p><p><strong>Error cases</strong></p><p>- `400 Bad Request` if the transport body itself cannot be decoded.<br>- GraphQL execution errors appear inside the GraphQL result payload.</p><p><strong><em>4. `GET /graphiql`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Routes/graphqlRoutes.swift">graphqlRoutes.swift:22</a></p><p><strong>Purpose</strong><br>Serve an in-browser GraphiQL interface for testing the API.</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Middleware involved</strong></p><p>- CORS<br>- Security headers<br>- Rate limiting: default rule `100 requests / 60 seconds`</p><p><strong>Response shape</strong><br>Static HTML page with embedded docs and a GraphiQL client.</p><p><strong>Important tradeoff</strong><br>This is excellent for developer ergonomics and questionable for unrestricted production exposure.</p><p><strong>GraphQL operations</strong></p><p>These are not separate HTTP routes, but they are separate public API operations and should be documented like first-class endpoints.</p><p><strong>5. GraphQL query `students`</strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift">GraphQLAPI.swift:22</a> and registered in the schema at <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift">GraphQLAPI.swift:188–190</a></p><p><strong>Purpose</strong><br>Return all students.</p><p><strong>Inputs</strong><br>None.</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Response shape</strong><br>List of `Student.Public` values.</p><p><strong>Error cases</strong><br>Database read errors bubble as GraphQL errors.</p><p><strong>Important tradeoff</strong><br>This exposes all students to any caller with no auth. That is fine for a demo and unacceptable for real user data.</p><p><strong><em>6. GraphQL query `student(id: UUID!)`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift">GraphQLAPI.swift:29</a></p><p><strong>Purpose</strong><br>Fetch a single student by ID.</p><p><strong>Inputs</strong></p><p>- `id: UUID!`</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Response shape</strong><br>`Student.Public` or `null`.</p><p><strong>Error cases</strong><br>Database read failures become GraphQL errors. Missing records return `null`, not `404`.</p><p><strong><em>7. GraphQL mutation `signup(input: StudentGraphQLCreateInput!)`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift">GraphQLAPI.swift:39</a></p><p><strong>Purpose</strong><br>Create a student through GraphQL.</p><p><strong>Inputs</strong></p><p>- `name`<br>- `email`<br>- `password`<br>- optional `dob`<br>- optional `phoneNumber`</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Response shape</strong><br>`Student.Public`</p><p><strong>Error cases</strong><br>Same practical failures as REST signup: body shape issues at GraphQL input parsing, unique email failures, DB errors.</p><p><strong>Important tradeoff</strong><br>This duplicates the REST signup behavior almost exactly.</p><p><strong><em>8. GraphQL mutation `login(input: StudentGraphQLLoginInput!)`</em></strong></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift"><em>GraphQLAPI.swift:64</em></a></p><p><strong>Purpose</strong><br>Authenticate and return a JWT plus public user data.</p><p><strong>Inputs</strong></p><p>- `email`<br>- `password`</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Response shape</strong></p><pre>{<br> &quot;data&quot;: {<br> &quot;login&quot;: {<br> &quot;user&quot;: {<br> &quot;id&quot;: &quot;UUID&quot;,<br> &quot;name&quot;: &quot;Graph User&quot;,<br> &quot;email&quot;: &quot;graphql@example.com&quot;<br> },<br> &quot;token&quot;: &quot;jwt-string&quot;<br> }<br> }<br>}</pre><p><strong>Error cases</strong><br>Invalid credentials become a GraphQL error derived from `Abort(.unauthorized, reason: “Invalid email or password”)`.</p><p><em>9. GraphQL mutation `updateStudent(input: StudentGraphQLUpdateInput!)`</em></p><p>Defined in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift"><em>GraphQLAPI.swift:86</em></a></p><p><strong>Purpose</strong><br>Update a student record by ID.</p><p><strong>Inputs</strong><br>The input type defines:</p><p>- `id: UUID`<br>- `dob: Date?`<br>- `name: String?`<br>- `phoneNumber: String?`</p><p>But only `id` and `dob` are registered in the GraphQL schema at <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/GraphQL/GraphQLAPI.swift"><em>GraphQLAPI.swift:182–185</em></a></p><p>That means `name` and `phoneNumber` exist in Swift but are not actually exposed in the GraphQL input schema.</p><p><strong>Authentication required</strong><br>No.</p><p><strong>Response shape</strong><br>Updated `Student.Public`.</p><p><strong>Error cases</strong></p><p>- `404`-equivalent GraphQL error if the student is not found.<br>- DB save failures surface as GraphQL errors.</p><p><strong>Important tradeoff</strong><br>This is the most sensitive route in the app. It mutates student data without authentication or authorization.</p><p><strong>Why mixing REST and GraphQL is useful here</strong></p><p>In a larger system, I would push hard for clearer boundaries. In this project, the duplication is educational.</p><p>It lets you compare:</p><p>- transport ergonomics,<br>- response modeling,<br>- error shapes,<br>- and the reuse of domain logic between controllers and GraphQL resolvers.</p><p>What it also reveals is that a shared security model has not been applied across both API styles. That is the biggest architectural lesson in the whole surface area.</p><p><strong>Key code snippets</strong></p><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Controllers/AuthController.swift"><em>AuthController.swift</em></a></p><pre>func boot(routes: any RoutesBuilder) throws {<br> let authRoutes = routes.grouped(&quot;auth&quot;)<br> authRoutes.post(&quot;signup&quot;, use: signup)<br> authRoutes.post(&quot;login&quot;, use: login)<br>}</pre><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Routes/graphqlRoutes.swift"><em>graphqlRoutes.swift</em></a></p><pre>app.post(&quot;graphql&quot;) { req async throws -&gt; Response in<br> let graphQLRequest = try req.content.decode(GraphQLRequestBody.self).graphQLRequest()<br> let result = try await api.execute(<br> request: graphQLRequest,<br> context: req,<br> on: req.application.eventLoopGroup<br> )<br> …<br>}</pre><p><strong>What to improve next</strong></p><p>- Add authenticated route groups for any student read or update operation.<br>- Decide whether the service wants REST, GraphQL, or both, then remove redundant paths.<br>- Standardize error payloads across REST and GraphQL-facing auth failures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=320342265cb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside the Vapor App: Bootstrapping, Configuration, and Runtime Shape — Part-2]]></title>
            <link>https://medium.com/@iosdevrajesh/inside-the-vapor-app-bootstrapping-configuration-and-runtime-shape-part-2-ecdb5ea515f0?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecdb5ea515f0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[vaporswift]]></category>
            <category><![CDATA[swiftonserver]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 19:16:01 GMT</pubDate>
            <atom:updated>2026-08-02T15:12:09.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92UjtM727-bXbayGXGtH0Q.jpeg" /></figure><p>From @main to database wiring, middleware registration, TLS, and migrations</p><blockquote>This article walks through how StudentAppBackend starts up. It explains the @main entrypoint, configure.swift, environment-based branching, MySQL setup, CORS, JWT signer registration, middleware order, auto-migrations, and optional TLS. It also calls out where the current configuration is practical for local experimentation but risky for production.</blockquote><p>The easiest way to misunderstand a backend is to start with the business logic. In a real server, the control plane matters just as much as the endpoints. How the app boots, what it configures globally, what it trusts from the environment, and which middleware runs first all shape the behavior of every request.</p><p>StudentAppBackend makes this especially clear because most of the app’s real architecture is concentrated in two files:</p><ul><li><a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/entrypoint.swift#L6">entrypoint.swift</a></li><li><a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift#L19">configure.swift</a></li></ul><h3>The real entrypoint is tiny</h3><p>The app starts exactly where you would expect in modern Vapor:</p><pre>@main<br>enum Entrypoint {<br>    static func main() async throws {<br>        var env = try Environment.detect()<br>        try LoggingSystem.bootstrap(from: &amp;env)<br><br>        let app = try await Application.make(env)<br>        do {<br>            try configure(app)<br>            try await app.execute()<br>        } catch {<br>            app.logger.report(error: error)<br>            try? await app.asyncShutdown()<br>            throw error<br>        }<br>        try await app.asyncShutdown()<br>    }<br>}</pre><p>This is a good shape. Environment.detect() lets Vapor choose modes like development or testing. Logging is bootstrapped before app construction. The real configuration work is delegated to configure(app), which keeps the lifecycle readable.</p><p>There is also a commented note about installing SwiftNIO’s event loop group as the global Swift Concurrency executor. That matters because it shows the author is aware of the Swift server runtime boundary between NIO and async/await. Even though it is not enabled, the comment is technically informed and points to a real performance/runtime consideration.</p><h3>configure.swift is where the backend actually becomes a backend</h3><p>If you want to understand this codebase, read <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift#L19">configure.swift</a> carefully.</p><p>This file is doing five important jobs:</p><ol><li>Configuring MySQL.</li><li>Registering global middleware.</li><li>Setting up JWT signing.</li><li>Running migrations automatically.</li><li>Optionally enabling TLS.</li></ol><p>That is the entire control plane.</p><h3>The app branches by environment</h3><p>The function switches on app.environment:</p><pre>switch app.environment {<br>case .testing:<br>    ...<br>default:<br>    ...<br>}</pre><p>This is a sensible start, but the details are revealing.</p><p>In .testing, the app:</p><ul><li>uses MySQL with DATABASE_* environment variables or local defaults,</li><li>disables DB certificate verification,</li><li>sets a CORS policy for <a href="https://studentapp.ddns.net,/">https://studentapp.ddns.net,</a></li><li>registers security headers middleware,</li><li>registers rate limiting,</li><li>installs an HS256 JWT signer with a hard-coded secret,</li><li>runs CreateStudent() migration,</li><li>and configures TLS directly with local certificate files while binding to 127.0.0.1:8443.</li></ul><p>In the default branch, the app:</p><ul><li>also uses MySQL with environment-variable fallbacks,</li><li>also disables DB certificate verification,</li><li>sets CORS to <a href="https://127.0.0.1:8080,">https://127.0.0.1:8080,</a></li><li>registers the same middleware,</li><li>conditionally enables HTTPS based on ENABLE_HTTPS plus certificate existence,</li><li>installs the same hard-coded HS256 JWT signer,</li><li>runs the same migration,</li><li>and registers routes.</li></ul><p>That tells us two things.</p><p>First, the app is deliberately shaped for local experimentation and ad hoc deployment rather than strict environment isolation.</p><p>Second, the testing branch is doing more than most teams would want a test environment to do. Direct TLS setup in tests and dependence on MySQL mean the tests are closer to integration tests than lightweight unit tests.</p><h3>Database configuration is practical, but not hardened</h3><p>The MySQL connection uses Fluent MySQL:</p><pre>app.databases.use(.mysql(<br>    hostname: Environment.get(&quot;DATABASE_HOST&quot;) ?? &quot;localhost&quot;,<br>    port: Environment.get(&quot;DATABASE_PORT&quot;).flatMap(Int.init(_:)) ?? MySQLConfiguration.ianaPortNumber,<br>    username: Environment.get(&quot;DATABASE_USER&quot;) ?? &quot;root&quot;,<br>    password: Environment.get(&quot;DATABASE_PASSWORD&quot;) ?? &quot;newpassword&quot;,<br>    database: Environment.get(&quot;DATABASE_NAME&quot;) ?? &quot;student_db&quot;,<br>    tlsConfiguration: {<br>        var tls = TLSConfiguration.makeClientConfiguration()<br>        tls.certificateVerification = .none<br>        return tls<br>    }()<br>), as: .mysql)</pre><p>This is acceptable for local Docker-based development. It is not acceptable as a production default. The line that disables certificate verification is the most important detail in the block. It means the app is willing to talk to MySQL over TLS without actually verifying the peer.</p><p>For experiments, that is common.</p><p>For real deployments, it weakens the whole trust model.</p><h3>Middleware order is deliberate, and that matters</h3><p>The middleware stack is registered in this order in both branches:</p><pre>app.middleware.use(cors)<br>app.middleware.use(SecurityHeadersMiddleware())<br>app.middleware.use(RateLimiterMiddleware())</pre><p>This order is not arbitrary.</p><ul><li>CORSMiddleware first makes sure browsers receive the correct CORS behavior as early as possible.</li><li>SecurityHeadersMiddleware adds response headers after downstream handling.</li><li>RateLimiterMiddleware runs before route handlers and can reject requests with 429 Too Many Requests.</li></ul><p>That order has a subtle effect. Because rate limiting happens after CORS middleware has already been inserted into the chain, even rate-limited browser requests should still have the CORS layer available. That is good API ergonomics.</p><h3>JWT is configured globally, but only for signing</h3><p>The JWT setup is one line:</p><pre>app.jwt.signers.use(.hs256(key: &quot;your-secret-key&quot;.data(using: .utf8)!))</pre><p>This is enough to sign and verify tokens with Vapor’s JWT support. But in this project, only token creation is implemented in request handlers. There is no route group that calls req.jwt.verify(...), no auth middleware based on StudentToken, and no protected resource using that identity.</p><p>So this configuration is real, but only half-used.</p><p>That is an important theme in this codebase. The project proves token issuance, not end-to-end authenticated request handling.</p><h3>Migrations are automatic</h3><p>The app registers one migration:</p><pre>app.migrations.add(CreateStudent())<br>try app.autoMigrate().wait()</pre><p>Auto-migrating on boot is convenient in development and demos. It is also the easiest way to hide migration failures until runtime. For this project, the tradeoff is acceptable, because there is only one migration and one table. For production, migrations usually belong in an explicit deploy step.</p><h3>TLS support is split across two styles</h3><p>This app supports HTTPS in two different ways:</p><ul><li>direct Vapor TLS configuration in configure.swift,</li><li>and reverse-proxy TLS through the repo’s Caddy and Docker setup described in README.md.</li></ul><p>The helper at <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift#L11">configure.swift:11</a> checks ENABLE_HTTPS plus certificate file existence:</p><pre>private func shouldEnableTLS(certPath: String, keyPath: String) -&gt; Bool {<br>    let flag = Environment.get(&quot;ENABLE_HTTPS&quot;)?.lowercased()<br>    let tlsRequested = flag == &quot;1&quot; || flag == &quot;true&quot; || flag == &quot;yes&quot;<br>    let hasTLSFiles = FileManager.default.fileExists(atPath: certPath)<br>        &amp;&amp; FileManager.default.fileExists(atPath: keyPath)<br>    return tlsRequested &amp;&amp; hasTLSFiles<br>}</pre><p>That is a decent local feature gate. The testing branch, however, unconditionally attempts to load certs and bind HTTPS on port 8443, which is more brittle than the default branch.</p><h3>The runtime flow is simple enough to diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKnZYAbScNetFUbfpVIGkw.png" /></figure><p>That is the good news. The boot shape is easy to reason about.</p><p>The less good news is that several production-sensitive defaults are still hard-coded or permissive:</p><ul><li>JWT secret is hard-coded.</li><li>DB TLS verification is disabled.</li><li>CORS origin values are manually fixed in code.</li><li>migrations run automatically on startup,</li><li>and debug environment variable dumps exist in the default branch under #if DEBUG.</li></ul><p>For an experiment, this is fair. For a deployable service, configuration needs to become stricter and more environment-driven.</p><h3>What this boot process gets right</h3><p>The project’s configuration is valuable because it is centralized. You can read one file and understand the runtime.</p><p>That is not glamorous, but it is exactly what you want when a backend starts growing. Many small backends become confusing because concerns scatter too early. Here, the app remains inspectable.</p><p>That inspectability is one of Swift’s underrated strengths on the server. When the code stays direct, the architecture stays legible.</p><h3>Key code snippets</h3><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift#L89">configure.swift</a>:</p><pre>let corsConfig = CORSMiddleware.Configuration(<br>    allowedOrigin: .custom(&quot;https://127.0.0.1:8080&quot;),<br>    allowedMethods: [.GET, .POST, .PUT, .DELETE, .OPTIONS],<br>    allowedHeaders: [.accept, .authorization, .contentType, .origin, .xRequestedWith],<br>    allowCredentials: true<br>)<br>let cors = CORSMiddleware(configuration: corsConfig)<br>app.middleware.use(cors)<br>app.middleware.use(SecurityHeadersMiddleware())<br>app.middleware.use(RateLimiterMiddleware())</pre><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Configure/configure.swift#L145">configure.swift</a>:</p><pre>app.jwt.signers.use(.hs256(key: &quot;your-secret-key&quot;.data(using: .utf8)!))<br>app.migrations.add(CreateStudent())<br>try app.autoMigrate().wait()<br>try routes(app)</pre><h3>What to improve next</h3><ul><li>Move JWT secrets, CORS origins, DB TLS mode, and HTTPS settings fully into environment configuration.</li><li>Stop using .wait() during startup where an async configuration path is available.</li><li>Make the .testing environment lighter and less dependent on local TLS assumptions.</li></ul><p><a href="https://medium.com/@iosdevrajesh/designing-the-api-surface-rest-graphql-and-route-registration-320342265cb2?sharedUserId=iosdevrajesh">Designing the API Surface: REST, GraphQL, and Route Registration — Part 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecdb5ea515f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Far Can Swift Go on the Server? -Part I]]></title>
            <link>https://medium.com/@iosdevrajesh/how-far-can-swift-go-on-the-server-part-i-a6ace79e715f?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ace79e715f</guid>
            <category><![CDATA[vaporswift]]></category>
            <category><![CDATA[swiftonserver]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 17:23:13 GMT</pubDate>
            <atom:updated>2026-08-02T15:08:45.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92UjtM727-bXbayGXGtH0Q.jpeg" /></figure><blockquote>This article introduces StudentAppBackend, a <a href="https://www.vapor.codes/">Vapor-based Swift </a>server that mixes REST and GraphQL, JWT auth, Fluent/MySQL persistence, and custom middleware. It explains why building a backend in pure Swift is technically interesting, where Swift feels genuinely strong on the server, and why this project is best understood as a serious experiment rather than a production-ready system.</blockquote><p>There are two common ways to talk about server-side Swift. The first is hype: one language everywhere, shared models, unified teams, and a neat conference talk. The second is dismissal: Swift is for Apple platforms, backend work belongs to Go, Node, Java, Rust, or Kotlin, and anything else is a novelty.</p><p>StudentAppBackend sits in the more interesting middle ground.</p><p>This repository is not trying to be a giant enterprise platform. It is a compact Vapor application with a small student domain, MySQL persistence, JWT login, a REST auth surface, and a parallel GraphQL API. That makes it exactly the kind of codebase worth studying. It is large enough to reveal real engineering tradeoffs, but small enough that you can still hold the whole thing in your head.</p><p>The first thing I like about this project is that it does not hide what it is. The structure under <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend">Sources/StudentAppBackend</a> is direct: configuration, controllers, models, migrations, GraphQL schema, routes, and one small service. This is not a framework demo pretending to be a backend. It is an actual backend prototype built with Vapor.</p><p>The second reason it is worth writing about is that it shows where Swift actually feels good on the server.</p><p>Swift gives this codebase a few real advantages:</p><ul><li>Strong data modeling for request and response types.</li><li>A readable async model that fits I/O-heavy server work.</li><li>Fluent and Vapor conventions that are much less magical than many dynamic stacks.</li><li>Shared language fluency for iOS teams that want to inspect backend code without changing mental gears.</li></ul><p>The core model, for example, is plain Swift. The Student model in <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Models/Student.swift#L13">Student.swift</a> defines storage fields, public projections, and request payloads in one place:</p><pre>final class Student: Model, Content, @unchecked Sendable {<br>    static let schema = &quot;students&quot;    <br>    @ID(key: .id)<br>    var id: UUID?    <br>    @Field(key: &quot;name&quot;)<br>    var name: String    <br>    @Field(key: &quot;email&quot;)<br>    var email: String<br>    @Field(key: &quot;passwordHash&quot;)<br>    var passwordHash: String<br>}</pre><p>If you are coming from iOS, that shape feels natural. If you are coming from backend work, it feels disciplined enough to be useful.</p><p>But the real value of this project is not that Swift can do backend work. We already know that. The value is that this repository shows exactly where a Swift backend becomes elegant, and exactly where it becomes dangerous if you stop too early.</p><p>For example:</p><ul><li>JWT signing is implemented, but JWT verification is not wired into protected routes.</li><li>Password hashing exists, but request validation does not.</li><li>Rate limiting exists, but only in memory.</li><li>Migrations exist, but data access boundaries are still thin.</li><li>GraphQL is present, but authorization is effectively absent.</li></ul><p>That combination makes StudentAppBackend useful as an engineering specimen. It is opinionated enough to teach from, and incomplete enough to discuss honestly.</p><p>The codebase also makes a more subtle point: Swift on the server is at its best when the backend is not trying to imitate another ecosystem. This app is most convincing when it leans into Vapor’s style, Swift’s types, and Fluent’s schema model. It is less convincing when security and production concerns are treated as future polish.</p><p>That is not a criticism of the project. It is the real lesson. Many experimental backends look clean because they avoid complexity. This backend looks interesting because it includes enough real concerns to show where the hard parts begin.</p><p>At a high level, the app has four layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fi9Xcyy8ZAvrcBdL19Cig.png" /></figure><p>That sounds ordinary, but the interesting part is how those pieces are wired. configure.swift builds database connectivity, middleware, JWT signing, migrations, and optional TLS. routes.swift registers a REST controller and GraphQL routes. AuthController.swift handles signup and login. GraphQLAPI.swift exposes student queries and mutations. RateLimiterMiddleware.swift adds a custom per-IP rule set. CreateStudent.swift defines the schema.</p><p>In other words, this is small, but it is not toy-sized.</p><p>Over the rest of this series, I am going to treat StudentAppBackend as if it were a real backend under technical review. That means:</p><ul><li>documenting every route and GraphQL operation,</li><li>tracing the boot flow from @main to middleware to handlers,</li><li>unpacking JWT design and its missing pieces,</li><li>explaining the rate limiter algorithm and its distributed-systems problems,</li><li>looking at schema design, error handling, and persistence,</li><li>and ending with a blunt answer to the question every backend eventually faces:</li></ul><p>Would I ship this?</p><p>As an experiment: yes.</p><p>As production infrastructure: not yet.</p><p>That tension is what makes the project worth reading.</p><h3>Key code snippets</h3><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/entrypoint.swift#L6">entrypoint.swift</a>:</p><pre>@main<br>enum Entrypoint {<br>    static func main() async throws {<br>        var env = try Environment.detect()<br>        try LoggingSystem.bootstrap(from: &amp;env)<br>        let app = try await Application.make(env)<br>        try configure(app)<br>        try await app.execute()<br>    }<br>}</pre><p>From <a href="https://github.com/rajeshm20/StudentAppBackend/blob/main/Sources/StudentAppBackend/Routes/routes.swift#L5">routes.swift</a>:</p><pre>func routes(_ app: Application) throws {<br>    try app.register(collection: AuthController())<br>    try registerGraphQLRoutes(app)<br>}</pre><h3>What to improve next</h3><ul><li>Add a protected route so JWT verification exists in the actual request path, not just in token issuance.</li><li>Add validation for email, password strength, and required fields before discussing security at all.</li><li>Separate “experiment-friendly” shortcuts from “production-safe” defaults through environment-based configuration.</li></ul><p><a href="https://medium.com/@iosdevrajesh/inside-the-vapor-app-bootstrapping-configuration-and-runtime-shape-part-2-ecdb5ea515f0?sharedUserId=iosdevrajesh">Inside the Vapor App: Bootstrapping, Configuration, and Runtime Shape — Part-2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ace79e715f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Strategies in SwiftUI]]></title>
            <link>https://medium.com/@iosdevrajesh/caching-strategies-in-swiftui-5fd7662a99e8?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd7662a99e8</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 16:57:52 GMT</pubDate>
            <atom:updated>2026-07-08T16:41:22.838Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A Practical Walkthrough with JSONPlaceholder</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o5lm9eJ1eeCLFKg8" /><figcaption>Photo by <a href="https://unsplash.com/@bluestonex_apphaus?utm_source=medium&amp;utm_medium=referral">Bluestonex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>How to stop your app from re-fetching the same data every time a screen appears — with working code you can drop into Xcode today.</em></p><h4><strong>The problem: every screen load pays full price</strong></h4><p>Here’s a scenario every iOS developer has lived through. A user taps into a post, reads it, hits back, then taps the <em>*same post*</em> again thirty seconds later. What happens? A brand-new network round trip. Same data, same server, same 300–800ms wait — and now a wasted API call and a chunk of the user’s data plan too.</p><p>The fix isn’t complicated, but it’s rarely done <em>well</em>. Most apps either cache nothing, or bolt on a single `<strong><em>NSCache</em></strong>` and call it done — which solves the in-session problem but loses everything the moment the app is force-quit. A production-grade solution needs to think in <strong><em>layers</em></strong>, because each layer trades off differently between speed, durability, and complexity.</p><p>This article builds exactly that: a small SwiftUI app hitting the free <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> API, with a full caching stack you can inspect in real time.</p><h4><strong>The three-tier mental model</strong></h4><p>Before any code, it’s worth naming the layers explicitly, because each one answers a different question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KCkD9Tx_WuM0Soa8waxr2Q.png" /></figure><p>A cache-aside read should walk this ladder top to bottom: check memory, then disk, then finally pay for the network — and on the way back up, <em>*promote*</em> whatever you found so the next read is one tier faster.</p><h4>Tier 1 + 2: a generic, actor-isolated cache manager</h4><p>The core of the system is a single actor that owns both the memory and disk tiers. Using an actor instead of a class with manual locks means every read and write is automatically serialized by the Swift compiler — no DispatchQueue, no NSLock, no risk of two threads corrupting the same cache entry.</p><pre>actor CacheManager {<br>    static let shared = CacheManager()<br><br>    private let memoryCache = NSCache&lt;NSString, CacheBox&gt;()<br>    private let diskDirectory: URL<br>    private var stats = CacheStats()<br><br>    private final class CacheBox {<br>        let payload: Data<br>        let timestamp: Date<br>        init(payload: Data, timestamp: Date) {<br>            self.payload = payload<br>            self.timestamp = timestamp<br>        }<br>    }<br><br>    private struct DiskEnvelope: Codable {<br>        let timestamp: Date<br>        let payload: Data<br>    }<br><br>    private init() {<br>        memoryCache.countLimit = 200<br>        memoryCache.totalCostLimit = 20 * 1024 * 1024 // 20 MB<br><br>        let cachesDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]<br>        diskDirectory = cachesDir.appendingPathComponent(&quot;CachingDemo&quot;, isDirectory: true)<br>        try? FileManager.default.createDirectory(at: diskDirectory, withIntermediateDirectories: true)<br>    }<br>}</pre><p>A few deliberate choices here worth calling out:</p><ul><li><strong>NSCache, not a </strong><strong>Dictionary.</strong> NSCache automatically evicts entries when the system is low on memory — a Dictionarywould happily hold onto everything until you crash. This is the same mechanism URLCache and UIKit&#39;s image caches use internally.</li><li><strong>CacheBox is a class, not a struct.</strong> NSCache requires reference types for its values, since it manages eviction by tracking object lifetimes.</li><li><strong>Every disk write is wrapped in a </strong><strong>DiskEnvelope</strong> that pairs the JSON payload with a timestamp. Without that timestamp sitting right next to the data, you can&#39;t cheaply answer &quot;is this still fresh?&quot; without extra file-system metadata calls.</li></ul><h4>Writing to both tiers at once</h4><pre>func store&lt;T: Codable&gt;(_ value: T, forKey key: String) throws {<br>    let payload = try JSONEncoder().encode(value)<br>    let timestamp = Date()<br><br>    memoryCache.setObject(<br>        CacheBox(payload: payload, timestamp: timestamp),<br>        forKey: key as NSString,<br>        cost: payload.count<br>    )<br><br>    let envelope = DiskEnvelope(timestamp: timestamp, payload: payload)<br>    let envelopeData = try JSONEncoder().encode(envelope)<br>    try envelopeData.write(to: fileURL(for: key), options: .atomic)<br>}</pre><p>One store call, one Codable value in, both tiers updated. The generic &lt;T: Codable&gt; means this same function handles [Post], [User], or any other model in the app — no duplicated caching code per type.</p><h3>Reading, with automatic promotion</h3><pre>func value&lt;T: Codable&gt;(_ type: T.Type, forKey key: String, maxAge: TimeInterval) -&gt; CacheResult&lt;T&gt; {<br>    let now = Date()<br><br>    if let box = memoryCache.object(forKey: key as NSString) {<br>        let age = now.timeIntervalSince(box.timestamp)<br>        if age &lt;= maxAge, let decoded = try? JSONDecoder().decode(type, from: box.payload) {<br>            stats.memoryHits += 1<br>            return CacheResult(value: decoded, source: .memory, isStale: false)<br>        } else {<br>            memoryCache.removeObject(forKey: key as NSString)<br>        }<br>    }<br><br>    let url = fileURL(for: key)<br>    if let raw = try? Data(contentsOf: url),<br>       let envelope = try? JSONDecoder().decode(DiskEnvelope.self, from: raw) {<br>        let age = now.timeIntervalSince(envelope.timestamp)<br>        if age &lt;= maxAge, let decoded = try? JSONDecoder().decode(type, from: envelope.payload) {<br>            // Promote back up to memory — the next read will be Tier 1.<br>            memoryCache.setObject(<br>                CacheBox(payload: envelope.payload, timestamp: envelope.timestamp),<br>                forKey: key as NSString,<br>                cost: envelope.payload.count<br>            )<br>            stats.diskHits += 1<br>            return CacheResult(value: decoded, source: .disk, isStale: false)<br>        } else {<br>            try? FileManager.default.removeItem(at: url)<br>        }<br>    }<br><br>    stats.misses += 1<br>    return CacheResult(value: nil, source: .miss, isStale: false)<br>}</pre><p>Notice the expiry check happens at <em>read</em> time, not write time — nothing proactively sweeps the cache on a timer. An expired entry is simply treated as a miss and deleted lazily, the moment it’s looked up. This keeps the whole design simple: no background timers to manage, no risk of a cleanup job firing at the wrong moment.</p><h3>Tier 3: letting the HTTP layer help too</h3><p>It’s easy to forget that URLSession already has a caching mechanism built in, driven by the server&#39;s Cache-Control headers. Wiring up a dedicated URLCache costs three lines and gives you a free layer underneath your own:</p><pre>private init() {<br>    let config = URLSessionConfiguration.default<br>    config.urlCache = URLCache(<br>        memoryCapacity: 10 * 1024 * 1024,<br>        diskCapacity: 50 * 1024 * 1024,<br>        directory: nil<br>    )<br>    config.requestCachePolicy = .useProtocolCachePolicy<br>    session = URLSession(configuration: config)<br>}</pre><p>This is a good reminder that “caching” in a real app is rarely one mechanism — it’s a stack, and the layers compose. Your app-level cache handles <em>what to show the user instantly</em>; URLCache handles <em>what the network stack itself doesn&#39;t need to re-transfer</em>.</p><h3>Making the strategy swappable</h3><pre>enum CachePolicy: String, CaseIterable, Identifiable {<br>    case cacheFirst = &quot;Cache First&quot;<br>    case networkFirst = &quot;Network First&quot;<br>    case staleWhileRevalidate = &quot;Stale-While-Revalidate&quot;<br>    case networkOnly = &quot;No Cache (Baseline)&quot;<br><br>    var id: String { rawValue }<br>}</pre><ul><li><strong>Cache First</strong> — check memory → disk → network, in that order. Best for data that rarely changes (a user’s own profile, a list of categories).</li><li><strong>Network First</strong> — always try the network for freshness, fall back to cache only if the request fails. Best when correctness matters more than speed, but you still want offline resilience.</li><li><strong>Stale-While-Revalidate</strong> — return whatever’s cached <em>immediately</em>, even if expired, then quietly refresh in the background. This is the best perceived-performance option: the user never sees a spinner for data they’ve seen before.</li><li><strong>No Cache</strong> — a deliberate non-cached baseline, useful mainly for demonstrating the difference (and for genuinely volatile data like a live stock ticker).</li></ul><p>The dispatch logic lives in one place:</p><pre>private func fetch&lt;T: Codable&gt;(key: String, url: URL, policy: CachePolicy) async throws -&gt; (value: T, source: CacheSource) {<br>    switch policy {<br>    case .cacheFirst:<br>        let cached = await cache.value(T.self, forKey: key, maxAge: ttl)<br>        if let value = cached.value { return (value, cached.source) }<br>        let value: T = try await request(url)<br>        try? await cache.store(value, forKey: key)<br>        return (value, .network)<br><br>    case .staleWhileRevalidate:<br>        if let stale: T = await cache.staleValue(T.self, forKey: key) {<br>            Task { [cache] in<br>                if let fresh: T = try? await self.request(url) {<br>                    try? await cache.store(fresh, forKey: key)<br>                }<br>            }<br>            return (stale, .disk)<br>        }<br>        let value: T = try await request(url)<br>        try? await cache.store(value, forKey: key)<br>        return (value, .network)<br><br>    // .networkFirst and .networkOnly follow the same pattern<br>    }<br>}</pre><p>The staleWhileRevalidate case is the one worth staring at: it returns synchronously-available data <em>and</em> kicks off a detached refresh Task that updates the cache for next time — without making the current screen wait on it.</p><h3>Seeing it, not just reading about it</h3><p>Code without a feedback loop is easy to misjudge, so the demo app surfaces the cache’s behavior directly in the UI: a colored badge on every screen shows whether that load came from <strong>Memory</strong> (green), <strong>Disk</strong> (blue), or <strong>Network</strong> (orange), next to the load time in milliseconds.</p><p>The test that matters: open a post, go back, open the <em>same</em> post again. With any real caching strategy selected, the second load flips to green and drops from ~400ms to single digits. Switch to the “No Cache” baseline and repeat the same steps — it stays orange and slow every time. That side-by-side is the entire pitch for why this matters, made visible instead of asserted.</p><p>A companion “Cache Stats” screen tracks memory hits, disk hits, network fetches, and overall hit rate — the same kind of dashboard you’d want in production to justify the engineering effort to a PM.</p><h3>Takeaways for your own apps</h3><ol><li><strong>Model caching as layers, not a single mechanism.</strong> Memory for speed, disk for durability, HTTP cache for the tier you get almost for free.</li><li><strong>Make the strategy a parameter, not a hard-coded assumption.</strong> A user’s own profile and a live price feed shouldn’t use the same cache policy — expose the choice.</li><li><strong>Actors remove an entire category of bugs.</strong> Thread-safety around a shared cache used to mean manual locks; in Swift Concurrency, an actor gets you there by construction.</li><li><strong>Expiry checks belong at read time.</strong> No background sweep jobs, no timers to leak — just treat a stale entry as a miss and let it clean itself up lazily.</li><li><strong>Instrument it.</strong> A hit-rate counter costs a few integers and turns “I think the cache is helping” into a number you can show your team.</li></ol><p>The full project — all source files, a working CachePolicy picker, and the stats dashboard — is available as a downloadable Xcode-ready package if you want to run it yourself rather than just read the snippets above.</p><p>demo code: <a href="https://github.com/rajeshm20/CachingDemo_iOS.git"><em>https://github.com/rajeshm20/CachingDemo_iOS.git</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd7662a99e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Senior Developer Interview Guide]]></title>
            <link>https://medium.com/@iosdevrajesh/ios-senior-developer-interview-guid-6bab91cccfb8?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bab91cccfb8</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Sun, 03 May 2026 17:39:23 GMT</pubDate>
            <atom:updated>2026-05-03T17:40:19.496Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mock++</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwAOWqLOtb85fsxGR_9hpA.png" /></figure><h3>1. Architecture &amp; Design</h3><h3>Explain MVVM + Clean Architecture</h3><p><strong>Answer:</strong> MVVM (Model-View-ViewModel) combined with Clean Architecture creates a scalable, testable iOS app structure. Clean Architecture adds layers of separation (Domain, Data, Presentation) to MVVM, ensuring business logic is independent of frameworks.</p><p><strong>Layers:</strong></p><ul><li><strong>Presentation Layer:</strong> View + ViewModel (UI logic)</li><li><strong>Domain Layer:</strong> Use Cases/Interactors + Entities (business logic)</li><li><strong>Data Layer:</strong> Repositories + Data Sources (network, database)</li></ul><pre>// Domain Layer - Entity<br>struct User {<br>    let id: String<br>    let name: String<br>    let email: String<br>}</pre><pre>// Domain Layer - Use Case Protocol<br>protocol FetchUserUseCaseProtocol {<br>    func execute(userId: String) async throws -&gt; User<br>}</pre><pre>// Domain Layer - Use Case Implementation<br>class FetchUserUseCase: FetchUserUseCaseProtocol {<br>    private let repository: UserRepositoryProtocol<br>    <br>    init(repository: UserRepositoryProtocol) {<br>        self.repository = repository<br>    }<br>    <br>    func execute(userId: String) async throws -&gt; User {<br>        return try await repository.getUser(id: userId)<br>    }<br>}</pre><pre>// Data Layer - Repository Protocol<br>protocol UserRepositoryProtocol {<br>    func getUser(id: String) async throws -&gt; User<br>}</pre><pre>// Data Layer - Repository Implementation<br>class UserRepository: UserRepositoryProtocol {<br>    private let remoteDataSource: UserRemoteDataSource<br>    <br>    init(remoteDataSource: UserRemoteDataSource) {<br>        self.remoteDataSource = remoteDataSource<br>    }<br>    <br>    func getUser(id: String) async throws -&gt; User {<br>        return try await remoteDataSource.fetchUser(id: id)<br>    }<br>}</pre><pre>// Presentation Layer - ViewModel<br>class UserViewModel: ObservableObject {<br>    @Published var user: User?<br>    @Published var errorMessage: String?<br>    @Published var isLoading = false<br>    <br>    private let fetchUserUseCase: FetchUserUseCaseProtocol<br>    <br>    init(fetchUserUseCase: FetchUserUseCaseProtocol) {<br>        self.fetchUserUseCase = fetchUserUseCase<br>    }<br>    <br>    func loadUser(userId: String) async {<br>        isLoading = true<br>        defer { isLoading = false }<br>        <br>        do {<br>            user = try await fetchUserUseCase.execute(userId: userId)<br>        } catch {<br>            errorMessage = error.localizedDescription<br>        }<br>    }<br>}</pre><h3>Scenario: Convert MVC to MVVM Following SOLID</h3><h4>Before (MVC):</h4><pre>class UserViewController: UIViewController {<br>    @IBOutlet weak var nameLabel: UILabel!<br>    @IBOutlet weak var emailLabel: UILabel!<br>    <br>    var userId: String?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        loadUser()<br>    }<br>    <br>    func loadUser() {<br>        guard let userId = userId else { return }<br>        <br>        // ❌ Violates Single Responsibility - VC handles networking<br>        let url = URL(string: &quot;https://api.example.com/users/\(userId)&quot;)!<br>        URLSession.shared.dataTask(with: url) { data, response, error in<br>            guard let data = data else { return }<br>            <br>            // ❌ Violates Single Responsibility - VC handles parsing<br>            let decoder = JSONDecoder()<br>            if let user = try? decoder.decode(User.self, from: data) {<br>                DispatchQueue.main.async {<br>                    // ❌ Massive View Controller<br>                    self.nameLabel.text = user.name<br>                    self.emailLabel.text = user.email<br>                }<br>            }<br>        }.resume()<br>    }<br>}</pre><h4>After (MVVM + SOLID):</h4><pre>// ✅ Single Responsibility Principle - Each class has one job<br>// ✅ Dependency Inversion Principle - Depend on abstractions<br>// Protocol (Abstraction)<br>protocol UserViewModelProtocol: ObservableObject {<br>    var userName: String { get }<br>    var userEmail: String { get }<br>    var isLoading: Bool { get }<br>    func loadUser(userId: String) async<br>}</pre><pre>// ViewModel<br>class UserViewModel: UserViewModelProtocol {<br>    @Published var userName: String = &quot;&quot;<br>    @Published var userEmail: String = &quot;&quot;<br>    @Published var isLoading: Bool = false<br>    <br>    private let userService: UserServiceProtocol<br>    <br>    // ✅ Dependency Injection<br>    init(userService: UserServiceProtocol) {<br>        self.userService = userService<br>    }<br>    <br>    func loadUser(userId: String) async {<br>        isLoading = true<br>        defer { isLoading = false }<br>        <br>        do {<br>            let user = try await userService.fetchUser(id: userId)<br>            userName = user.name<br>            userEmail = user.email<br>        } catch {<br>            print(&quot;Error: \(error)&quot;)<br>        }<br>    }<br>}</pre><pre>// Service Protocol<br>protocol UserServiceProtocol {<br>    func fetchUser(id: String) async throws -&gt; User<br>}</pre><pre>// Service Implementation<br>class UserService: UserServiceProtocol {<br>    private let networkManager: NetworkManagerProtocol<br>    <br>    init(networkManager: NetworkManagerProtocol) {<br>        self.networkManager = networkManager<br>    }<br>    <br>    func fetchUser(id: String) async throws -&gt; User {<br>        let endpoint = &quot;/users/\(id)&quot;<br>        return try await networkManager.request(endpoint: endpoint)<br>    }<br>}</pre><pre>// SwiftUI View<br>struct UserView: View {<br>    @StateObject var viewModel: UserViewModel<br>    let userId: String<br>    <br>    var body: some View {<br>        VStack {<br>            if viewModel.isLoading {<br>                ProgressView()<br>            } else {<br>                Text(viewModel.userName)<br>                Text(viewModel.userEmail)<br>            }<br>        }<br>        .task {<br>            await viewModel.loadUser(userId: userId)<br>        }<br>    }<br>}</pre><h3>Clean Architecture Data Flow</h3><p><strong>Flow:</strong> View → ViewModel → Use Case → Repository → Data Source → API</p><p><strong>Key Principle:</strong> Dependencies point inward. Outer layers depend on inner layers, never the reverse. The Domain layer (business logic) doesn’t know about UI or framework details.</p><h3>VIPER Components</h3><ul><li><strong>Interactor:</strong> Contains business logic, executes use cases, communicates with repositories</li><li><strong>Presenter:</strong> Formats data for display, handles user interactions, tells View what to show</li><li><strong>Entity:</strong> Plain data models (structs/classes) representing business objects</li><li><strong>View:</strong> Displays data and captures user input</li><li><strong>Router:</strong> Handles navigation between screens</li></ul><pre>// VIPER Example<br>protocol UserListViewProtocol: AnyObject {<br>    func showUsers(_ users: [User])<br>    func showError(_ message: String)<br>}</pre><pre>protocol UserListPresenterProtocol {<br>    func viewDidLoad()<br>    func didSelectUser(at index: Int)<br>}</pre><pre>protocol UserListInteractorProtocol {<br>    func fetchUsers() async throws -&gt; [User]<br>}</pre><pre>protocol UserListRouterProtocol {<br>    func navigateToUserDetail(user: User)<br>}</pre><pre>// Presenter<br>class UserListPresenter: UserListPresenterProtocol {<br>    weak var view: UserListViewProtocol?<br>    var interactor: UserListInteractorProtocol?<br>    var router: UserListRouterProtocol?<br>    <br>    private var users: [User] = []<br>    <br>    func viewDidLoad() {<br>        Task {<br>            do {<br>                users = try await interactor?.fetchUsers() ?? []<br>                view?.showUsers(users)<br>            } catch {<br>                view?.showError(error.localizedDescription)<br>            }<br>        }<br>    }<br>    <br>    func didSelectUser(at index: Int) {<br>        let user = users[index]<br>        router?.navigateToUserDetail(user: user)<br>    }<br>}</pre><h3>MVVM Data Flow</h3><p><strong>Flow:</strong></p><ol><li><strong>View</strong> binds to <strong>ViewModel</strong> properties (@Published, @State)</li><li>User interaction triggers <strong>ViewModel</strong> methods</li><li><strong>ViewModel</strong> updates <strong>Model</strong> (via services/repositories)</li><li><strong>Model</strong> changes publish to <strong>ViewModel</strong></li><li><strong>ViewModel</strong> updates published properties</li><li><strong>View</strong> automatically re-renders</li></ol><h3>Integrate SwiftUI into UIKit</h3><pre>import UIKit<br>import SwiftUI<br><br>// Method 1: Using UIHostingController<br>class MainViewController: UIViewController {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // Create SwiftUI View<br>        let swiftUIView = UserProfileView(userId: &quot;123&quot;)<br>        <br>        // Wrap in UIHostingController<br>        let hostingController = UIHostingController(rootView: swiftUIView)<br>        <br>        // Add as child view controller<br>        addChild(hostingController)<br>        view.addSubview(hostingController.view)<br>        <br>        // Setup constraints<br>        hostingController.view.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),<br>            hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>            hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)<br>        ])<br>        <br>        hostingController.didMove(toParent: self)<br>    }<br>}</pre><pre>// Method 2: Presenting SwiftUI modally<br>extension UIViewController {<br>    func presentSwiftUIView() {<br>        let swiftUIView = SettingsView()<br>        let hostingController = UIHostingController(rootView: swiftUIView)<br>        present(hostingController, animated: true)<br>    }<br>}</pre><h3>Data Binding in SwiftUI vs UIKit</h3><h4>SwiftUI (Built-in):</h4><pre>// SwiftUI - Automatic binding<br>class ViewModel: ObservableObject {<br>    @Published var username: String = &quot;&quot;<br>    @Published var count: Int = 0<br>}</pre><pre>struct ContentView: View {<br>    @StateObject var viewModel = ViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            // Two-way binding<br>            TextField(&quot;Username&quot;, text: $viewModel.username)<br>            <br>            // One-way binding<br>            Text(&quot;Count: \(viewModel.count)&quot;)<br>            <br>            Button(&quot;Increment&quot;) {<br>                viewModel.count += 1<br>            }<br>        }<br>    }<br>}</pre><h4>UIKit (Combine):</h4><pre>import UIKit<br>import Combine<br><br>class ViewController: UIViewController {<br>    private let viewModel = ViewModel()<br>    private var cancellables = Set()<br>    <br>    private let usernameTextField = UITextField()<br>    private let countLabel = UILabel()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupBindings()<br>    }<br>    <br>    private func setupBindings() {<br>        // Bind ViewModel → View (one-way)<br>        viewModel.$username<br>            .sink { [weak self] username in<br>                self?.usernameTextField.text = username<br>            }<br>            .store(in: &amp;cancellables)<br>        <br>        viewModel.$count<br>            .map { &quot;Count: \($0)&quot; }<br>            .assign(to: \.text, on: countLabel)<br>            .store(in: &amp;cancellables)<br>        <br>        // Bind View → ViewModel (two-way)<br>        NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification, object: usernameTextField)<br>            .compactMap { ($0.object as? UITextField)?.text }<br>            .assign(to: \.username, on: viewModel)<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>Singleton Pattern</h3><p><strong>Use Case:</strong> When you need exactly one instance of a class throughout the app lifecycle (NetworkManager, UserSession, AppConfiguration).</p><pre>// Basic Singleton<br>class NetworkManager {<br>    static let shared = NetworkManager()<br>    <br>    private init() {<br>        // Prevent external initialization<br>    }<br>    <br>    func request(url: URL) async throws -&gt; Data {<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        return data<br>    }<br>}</pre><pre>// Usage<br>let data = try await NetworkManager.shared.request(url: apiURL)</pre><pre>// Thread-Safe Singleton with lazy initialization<br>class DatabaseManager {<br>    static let shared: DatabaseManager = {<br>        let instance = DatabaseManager()<br>        instance.configure()<br>        return instance<br>    }()<br>    <br>    private init() {}<br>    <br>    private func configure() {<br>        // Setup database<br>    }<br>}</pre><pre>// Testable Singleton Pattern (Better)<br>protocol NetworkManagerProtocol {<br>    func request(url: URL) async throws -&gt; Data<br>}</pre><pre>class NetworkManager: NetworkManagerProtocol {<br>    static let shared: NetworkManagerProtocol = NetworkManager()<br>    <br>    private init() {}<br>    <br>    func request(url: URL) async throws -&gt; Data {<br>        let (data, _) = try await URLSession.shared.data(from: url)<br>        return data<br>    }<br>}</pre><pre>// For testing, inject mock<br>class MockNetworkManager: NetworkManagerProtocol {<br>    func request(url: URL) async throws -&gt; Data {<br>        return Data()<br>    }<br>}</pre><p><strong>Why Singleton for Network Layer?</strong></p><ul><li>Centralized configuration (headers, timeouts, interceptors)</li><li>Single URLSession instance (connection pooling, performance)</li><li>Consistent error handling and logging</li><li>Easier to manage authentication tokens</li></ul><h3>Why mutating Keyword Not Used in Classes?</h3><p><strong>Answer:</strong> The mutating keyword is only needed for <strong>value types</strong> (struct, enum) because they are copied when passed around. Classes are <strong>reference types</strong>, so modifying properties doesn&#39;t create a new instance.</p><pre>// Struct (Value Type) - needs mutating<br>struct Counter {<br>    var count: Int = 0<br>    <br>    mutating func increment() {<br>        count += 1  // Modifies self, needs &#39;mutating&#39;<br>    }<br>}</pre><pre>var counter = Counter()<br>counter.increment()  // ✅ Works</pre><pre>let immutableCounter = Counter()<br>// immutableCounter.increment()  // ❌ Error: cannot use mutating on &#39;let&#39;</pre><pre>// Class (Reference Type) - no mutating needed<br>class CounterClass {<br>    var count: Int = 0<br>    <br>    func increment() {<br>        count += 1  // ✅ No &#39;mutating&#39; needed<br>    }<br>}</pre><pre>let counterObj = CounterClass()<br>counterObj.increment()  // ✅ Works even with &#39;let&#39;</pre><h3>2. Design Patterns</h3><h3>Creational Patterns</h3><p><strong>Purpose:</strong> Deal with object creation mechanisms.</p><h4>1. Singleton</h4><pre>class AppConfig {<br>    static let shared = AppConfig()<br>    private init() {}<br>    <br>    var apiKey: String = &quot;abc123&quot;<br>}</pre><h4>2. Factory Pattern</h4><pre>protocol Vehicle {<br>    func drive()<br>}</pre><pre>class Car: Vehicle {<br>    func drive() { print(&quot;Driving car&quot;) }<br>}</pre><pre>class Bike: Vehicle {<br>    func drive() { print(&quot;Riding bike&quot;) }<br>}</pre><pre>class VehicleFactory {<br>    static func createVehicle(type: String) -&gt; Vehicle? {<br>        switch type {<br>        case &quot;car&quot;: return Car()<br>        case &quot;bike&quot;: return Bike()<br>        default: return nil<br>        }<br>    }<br>}</pre><pre>// Usage<br>let vehicle = VehicleFactory.createVehicle(type: &quot;car&quot;)<br>vehicle?.drive()</pre><h4>3. Builder Pattern</h4><p><strong>Use Case:</strong> Construct complex objects step by step (e.g., HTTP Request, Complex UI).</p><pre>struct HTTPRequest {<br>    let url: String<br>    let method: String<br>    let headers: [String: String]<br>    let body: Data?<br>    let timeout: TimeInterval<br>}</pre><pre>class HTTPRequestBuilder {<br>    private var url: String = &quot;&quot;<br>    private var method: String = &quot;GET&quot;<br>    private var headers: [String: String] = [:]<br>    private var body: Data?<br>    private var timeout: TimeInterval = 30<br>    <br>    func setURL(_ url: String) -&gt; HTTPRequestBuilder {<br>        self.url = url<br>        return self<br>    }<br>    <br>    func setMethod(_ method: String) -&gt; HTTPRequestBuilder {<br>        self.method = method<br>        return self<br>    }<br>    <br>    func addHeader(key: String, value: String) -&gt; HTTPRequestBuilder {<br>        self.headers[key] = value<br>        return self<br>    }<br>    <br>    func setBody(_ body: Data) -&gt; HTTPRequestBuilder {<br>        self.body = body<br>        return self<br>    }<br>    <br>    func setTimeout(_ timeout: TimeInterval) -&gt; HTTPRequestBuilder {<br>        self.timeout = timeout<br>        return self<br>    }<br>    <br>    func build() -&gt; HTTPRequest {<br>        return HTTPRequest(<br>            url: url,<br>            method: method,<br>            headers: headers,<br>            body: body,<br>            timeout: timeout<br>        )<br>    }<br>}</pre><pre>// Usage<br>let request = HTTPRequestBuilder()<br>    .setURL(&quot;https://api.example.com/users&quot;)<br>    .setMethod(&quot;POST&quot;)<br>    .addHeader(key: &quot;Content-Type&quot;, value: &quot;application/json&quot;)<br>    .addHeader(key: &quot;Authorization&quot;, value: &quot;Bearer token&quot;)<br>    .setTimeout(60)<br>    .build()</pre><h4>4. Prototype Pattern</h4><pre>protocol Copyable {<br>    func clone() -&gt; Self<br>}</pre><pre>class Document: Copyable {<br>    var title: String<br>    var content: String<br>    <br>    init(title: String, content: String) {<br>        self.title = title<br>        self.content = content<br>    }<br>    <br>    func clone() -&gt; Document {<br>        return Document(title: self.title, content: self.content)<br>    }<br>}</pre><pre>let original = Document(title: &quot;Report&quot;, content: &quot;Data...&quot;)<br>let copy = original.clone()</pre><h3>Abstract Factory Pattern</h3><p><strong>Real-World Use:</strong> Creating platform-specific UI components (iOS vs macOS).</p><pre>// Abstract Products<br>protocol Button {<br>    func render()<br>}</pre><pre>protocol TextField {<br>    func render()<br>}</pre><pre>// Concrete Products - iOS<br>class IOSButton: Button {<br>    func render() { print(&quot;iOS Button&quot;) }<br>}</pre><pre>class IOSTextField: TextField {<br>    func render() { print(&quot;iOS TextField&quot;) }<br>}</pre><pre>// Concrete Products - macOS<br>class MacButton: Button {<br>    func render() { print(&quot;Mac Button&quot;) }<br>}</pre><pre>class MacTextField: TextField {<br>    func render() { print(&quot;Mac TextField&quot;) }<br>}</pre><pre>// Abstract Factory<br>protocol UIFactory {<br>    func createButton() -&gt; Button<br>    func createTextField() -&gt; TextField<br>}</pre><pre>// Concrete Factories<br>class IOSFactory: UIFactory {<br>    func createButton() -&gt; Button { IOSButton() }<br>    func createTextField() -&gt; TextField { IOSTextField() }<br>}</pre><pre>class MacFactory: UIFactory {<br>    func createButton() -&gt; Button { MacButton() }<br>    func createTextField() -&gt; TextField { MacTextField() }<br>}</pre><pre>// Usage<br>class App {<br>    let factory: UIFactory<br>    <br>    init(factory: UIFactory) {<br>        self.factory = factory<br>    }<br>    <br>    func createUI() {<br>        let button = factory.createButton()<br>        let textField = factory.createTextField()<br>        <br>        button.render()<br>        textField.render()<br>    }<br>}</pre><pre>// Client code<br>#if os(iOS)<br>let factory = IOSFactory()<br>#else<br>let factory = MacFactory()<br>#endif</pre><pre>let app = App(factory: factory)<br>app.createUI()</pre><h3>Structural Patterns</h3><p><strong>Purpose:</strong> Deal with object composition and relationships between objects.</p><h4>1. Adapter Pattern</h4><pre>// Legacy class<br>class OldPaymentGateway {<br>    func makePayment(amount: Double) {<br>        print(&quot;Processing $\(amount) via old gateway&quot;)<br>    }<br>}</pre><pre>// New interface<br>protocol PaymentProcessor {<br>    func processPayment(amount: Double, currency: String)<br>}</pre><pre>// Adapter<br>class PaymentAdapter: PaymentProcessor {<br>    private let oldGateway: OldPaymentGateway<br>    <br>    init(oldGateway: OldPaymentGateway) {<br>        self.oldGateway = oldGateway<br>    }<br>    <br>    func processPayment(amount: Double, currency: String) {<br>        print(&quot;Converting \(currency) to USD&quot;)<br>        oldGateway.makePayment(amount: amount)<br>    }<br>}</pre><pre>// Usage<br>let adapter = PaymentAdapter(oldGateway: OldPaymentGateway())<br>adapter.processPayment(amount: 100, currency: &quot;EUR&quot;)</pre><h4>2. Decorator Pattern</h4><pre>protocol Coffee {<br>    func cost() -&gt; Double<br>    func description() -&gt; String<br>}</pre><pre>class SimpleCoffee: Coffee {<br>    func cost() -&gt; Double { 5.0 }<br>    func description() -&gt; String { &quot;Simple coffee&quot; }<br>}</pre><pre>class MilkDecorator: Coffee {<br>    private let coffee: Coffee<br>    <br>    init(coffee: Coffee) {<br>        self.coffee = coffee<br>    }<br>    <br>    func cost() -&gt; Double {<br>        coffee.cost() + 1.5<br>    }<br>    <br>    func description() -&gt; String {<br>        coffee.description() + &quot; + Milk&quot;<br>    }<br>}</pre><pre>class SugarDecorator: Coffee {<br>    private let coffee: Coffee<br>    <br>    init(coffee: Coffee) {<br>        self.coffee = coffee<br>    }<br>    <br>    func cost() -&gt; Double {<br>        coffee.cost() + 0.5<br>    }<br>    <br>    func description() -&gt; String {<br>        coffee.description() + &quot; + Sugar&quot;<br>    }<br>}</pre><pre>// Usage<br>var coffee: Coffee = SimpleCoffee()<br>coffee = MilkDecorator(coffee: coffee)<br>coffee = SugarDecorator(coffee: coffee)</pre><pre>print(coffee.description())  // &quot;Simple coffee + Milk + Sugar&quot;<br>print(coffee.cost())  // 7.0</pre><h3>Behavioral Patterns</h3><p><strong>Purpose:</strong></p><p>Deal with object communication and responsibility distribution.</p><h4>1. Observer Pattern (Delegation)</h4><pre>protocol DownloadDelegate: AnyObject {<br>    func downloadDidComplete(data: Data)<br>    func downloadDidFail(error: Error)<br>}</pre><pre>class Downloader {<br>    weak var delegate: DownloadDelegate?<br>    <br>    func startDownload(url: URL) {<br>        URLSession.shared.dataTask(with: url) { [weak self] data, response, error in<br>            if let error = error {<br>                self?.delegate?.downloadDidFail(error: error)<br>            } else if let data = data {<br>                self?.delegate?.downloadDidComplete(data: data)<br>            }<br>        }.resume()<br>    }<br>}</pre><pre>class ViewController: DownloadDelegate {<br>    let downloader = Downloader()<br>    <br>    func setup() {<br>        downloader.delegate = self<br>    }<br>    <br>    func downloadDidComplete(data: Data) {<br>        print(&quot;Downloaded \(data.count) bytes&quot;)<br>    }<br>    <br>    func downloadDidFail(error: Error) {<br>        print(&quot;Error: \(error)&quot;)<br>    }<br>}</pre><h4>2. Strategy Pattern</h4><pre>protocol PaymentStrategy {<br>    func pay(amount: Double)<br>}</pre><pre>class CreditCardPayment: PaymentStrategy {<br>    func pay(amount: Double) {<br>        print(&quot;Paid $\(amount) via Credit Card&quot;)<br>    }<br>}</pre><pre>class PayPalPayment: PaymentStrategy {<br>    func pay(amount: Double) {<br>        print(&quot;Paid $\(amount) via PayPal&quot;)<br>    }<br>}</pre><pre>class ShoppingCart {<br>    private var paymentStrategy: PaymentStrategy<br>    <br>    init(paymentStrategy: PaymentStrategy) {<br>        self.paymentStrategy = paymentStrategy<br>    }<br>    <br>    func setPaymentStrategy(_ strategy: PaymentStrategy) {<br>        self.paymentStrategy = strategy<br>    }<br>    <br>    func checkout(amount: Double) {<br>        paymentStrategy.pay(amount: amount)<br>    }<br>}</pre><pre>// Usage<br>let cart = ShoppingCart(paymentStrategy: CreditCardPayment())<br>cart.checkout(amount: 100)  // Credit Card</pre><pre>cart.setPaymentStrategy(PayPalPayment())<br>cart.checkout(amount: 50)  // PayPal</pre><h4>3. Command Pattern</h4><pre>protocol Command {<br>    func execute()<br>    func undo()<br>}</pre><pre>class Light {<br>    func turnOn() { print(&quot;Light ON&quot;) }<br>    func turnOff() { print(&quot;Light OFF&quot;) }<br>}</pre><pre>class LightOnCommand: Command {<br>    private let light: Light<br>    <br>    init(light: Light) {<br>        self.light = light<br>    }<br>    <br>    func execute() {<br>        light.turnOn()<br>    }<br>    <br>    func undo() {<br>        light.turnOff()<br>    }<br>}</pre><pre>class RemoteControl {<br>    private var command: Command?<br>    <br>    func setCommand(_ command: Command) {<br>        self.command = command<br>    }<br>    <br>    func pressButton() {<br>        command?.execute()<br>    }<br>    <br>    func pressUndo() {<br>        command?.undo()<br>    }<br>}</pre><pre>// Usage<br>let light = Light()<br>let lightOn = LightOnCommand(light: light)<br>let remote = RemoteControl()</pre><pre>remote.setCommand(lightOn)<br>remote.pressButton()  // Light ON<br>remote.pressUndo()    // Light OFF</pre><h3>3. Networking &amp; Combine</h3><h3>URLSession with Combine</h3><pre>import Combine<br>import Foundation</pre><pre>struct Post: Codable {<br>    let id: Int<br>    let title: String<br>    let body: String<br>}</pre><pre>class NetworkService {<br>    private var cancellables = Set()<br>    <br>    func fetchPosts() -&gt; AnyPublisher&lt;[Post], Error&gt; {<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!<br>        <br>        return URLSession.shared.dataTaskPublisher(for: url)<br>            .map(\.data)<br>            .decode(type: [Post].self, decoder: JSONDecoder())<br>            .receive(on: DispatchQueue.main)<br>            .eraseToAnyPublisher()<br>    }<br>    <br>    func fetchPostsWithErrorHandling() -&gt; AnyPublisher&lt;[Post], Never&gt; {<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!<br>        <br>        return URLSession.shared.dataTaskPublisher(for: url)<br>            .map(\.data)<br>            .decode(type: [Post].self, decoder: JSONDecoder())<br>            .catch { error -&gt; Just&lt;[Post]&gt; in<br>                print(&quot;Error: \(error)&quot;)<br>                return Just([])<br>            }<br>            .receive(on: DispatchQueue.main)<br>            .eraseToAnyPublisher()<br>    }<br>}</pre><pre>// Usage<br>class ViewModel: ObservableObject {<br>    @Published var posts: [Post] = []<br>    private var cancellables = Set()<br>    private let networkService = NetworkService()<br>    <br>    func loadPosts() {<br>        networkService.fetchPosts()<br>            .sink(receiveCompletion: { completion in<br>                switch completion {<br>                case .finished:<br>                    print(&quot;Finished loading posts&quot;)<br>                case .failure(let error):<br>                    print(&quot;Error: \(error)&quot;)<br>                }<br>            }, receiveValue: { [weak self] posts in<br>                self?.posts = posts<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>Publisher and Subscriber in Combine</h3><p><strong>Publisher:</strong> Emits values over time. Can complete successfully or with an error.</p><p><strong>Subscriber:</strong> Receives values from a Publisher.</p><pre>import Combine<br>// Custom Publisher<br>class TemperatureSensor {<br>    let temperaturePublisher = PassthroughSubject()<br>    <br>    func simulateTemperatureChange() {<br>        temperaturePublisher.send(25.0)<br>        temperaturePublisher.send(26.5)<br>        temperaturePublisher.send(24.8)<br>        temperaturePublisher.send(completion: .finished)<br>    }<br>}</pre><pre>// Subscriber using sink<br>let sensor = TemperatureSensor()<br>var cancellable: AnyCancellable?</pre><pre>cancellable = sensor.temperaturePublisher<br>    .sink(<br>        receiveCompletion: { completion in<br>            print(&quot;Completed: \(completion)&quot;)<br>        },<br>        receiveValue: { temperature in<br>            print(&quot;Temperature: \(temperature)°C&quot;)<br>        }<br>    )</pre><pre>sensor.simulateTemperatureChange()</pre><pre>// Publisher types<br>let justPublisher = Just(42)  // Emits one value then completes<br>let futurePublisher = Future { promise in<br>    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>        promise(.success(100))<br>    }<br>}</pre><pre>// Subject types<br>let passthroughSubject = PassthroughSubject()  // Doesn&#39;t hold value<br>let currentValueSubject = CurrentValueSubject(&quot;Initial&quot;)  // Holds current value</pre><h3>Combine Operators</h3><pre>import Combine<br>// Map - Transform values<br>Just(5)<br>    .map { $0 * 2 }<br>    .sink { print($0) }  // 10<br>// Filter - Filter values based on condition<br>[1, 2, 3, 4, 5].publisher<br>    .filter { $0 % 2 == 0 }<br>    .sink { print($0) }  // 2, 4<br>// CompactMap - Remove nils<br>[&quot;1&quot;, &quot;2&quot;, &quot;abc&quot;, &quot;3&quot;].publisher<br>    .compactMap { Int($0) }<br>    .sink { print($0) }  // 1, 2, 3<br>// FlatMap - Transform and flatten<br>struct User {<br>    let id: Int<br>    func fetchProfile() -&gt; AnyPublisher {<br>        Just(&quot;Profile for user \(id)&quot;).eraseToAnyPublisher()<br>    }<br>}<br>Just(User(id: 1))<br>    .flatMap { $0.fetchProfile() }<br>    .sink { print($0) }<br>// Debounce - Wait for pause in events<br>let searchText = PassthroughSubject()<br>searchText<br>    .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)<br>    .sink { print(&quot;Search: \($0)&quot;) }<br>searchText.send(&quot;a&quot;)<br>searchText.send(&quot;ap&quot;)<br>searchText.send(&quot;app&quot;)<br>// Only prints &quot;Search: app&quot; after 500ms pause<br>// CombineLatest - Combine multiple publishers<br>let username = CurrentValueSubject(&quot;&quot;)<br>let password = CurrentValueSubject(&quot;&quot;)<br>Publishers.CombineLatest(username, password)<br>    .map { username, password in<br>        return !username.isEmpty &amp;&amp; password.count &gt;= 6<br>    }<br>    .sink { isValid in<br>        print(&quot;Form valid: \(isValid)&quot;)<br>    }<br>// Merge - Combine values from multiple publishers<br>let publisher1 = PassthroughSubject()<br>let publisher2 = PassthroughSubject()<br>Publishers.Merge(publisher1, publisher2)<br>    .sink { print($0) }<br>publisher1.send(1)<br>publisher2.send(2)<br>// Prints: 1, 2<br>// Zip - Pair values from publishers<br>let numbers = [1, 2, 3].publisher<br>let letters = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;].publisher<br>Publishers.Zip(numbers, letters)<br>    .sink { print(&quot;\($0)-\($1)&quot;) }<br>// Prints: 1-A, 2-B, 3-C</pre><h3>Cancellation in Combine</h3><pre>import Combine<br><br>class DataFetcher {<br>    private var cancellables = Set()<br>    <br>    func fetchData() {<br>        // Store cancellable in Set<br>        URLSession.shared.dataTaskPublisher(for: URL(string: &quot;https://api.example.com&quot;)!)<br>            .sink(receiveCompletion: { _ in },<br>                  receiveValue: { _ in })<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    func cancelAll() {<br>        // Cancel all stored subscriptions<br>        cancellables.removeAll()<br>    }<br>    <br>    func fetchWithManualCancellation() -&gt; AnyCancellable {<br>        // Return cancellable for manual cancellation<br>        return URLSession.shared.dataTaskPublisher(for: URL(string: &quot;https://api.example.com&quot;)!)<br>            .sink(receiveCompletion: { _ in },<br>                  receiveValue: { _ in })<br>    }<br>}</pre><pre>// Usage<br>let fetcher = DataFetcher()<br>fetcher.fetchData()</pre><pre>// Cancel specific request<br>let cancellable = fetcher.fetchWithManualCancellation()<br>cancellable.cancel()</pre><pre>// Cancel all<br>fetcher.cancelAll()</pre><pre>// Automatic cancellation when deinit<br>class ViewModel {<br>    private var cancellables = Set()<br>    <br>    deinit {<br>        // Automatically cancelled when ViewModel is deallocated<br>        print(&quot;Cancelling all subscriptions&quot;)<br>    }<br>}</pre><h3>4. Security &amp; Cryptography</h3><h3>Certificate Pinning vs Public Key Pinning</h3><h4>Certificate Pinning:</h4><p>Pin the entire SSL certificate. Certificate expires → app breaks until updated.</p><h4>Public Key Pinning (Better):</h4><p>Pin only the public key from the certificate. Certificate can be renewed without app update as long as the key pair remains the same.</p><pre>import Foundation<br>import Security<br><br>class SSLPinningManager: NSObject {<br>    <br>    // Public Key Pinning<br>    func urlSession(<br>        _ session: URLSession,<br>        didReceive challenge: URLAuthenticationChallenge,<br>        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void<br>    ) {<br>        guard let serverTrust = challenge.protectionSpace.serverTrust else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br>        <br>        // Get server public key<br>        guard let serverPublicKey = SecTrustCopyKey(serverTrust) else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br>        <br>        // Get pinned public key from bundle<br>        guard let pinnedPublicKey = getPinnedPublicKey() else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br>        <br>        // Compare keys<br>        if serverPublicKey == pinnedPublicKey {<br>            let credential = URLCredential(trust: serverTrust)<br>            completionHandler(.useCredential, credential)<br>        } else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>        }<br>    }<br>    <br>    private func getPinnedPublicKey() -&gt; SecKey? {<br>        guard let certPath = Bundle.main.path(forResource: &quot;certificate&quot;, ofType: &quot;cer&quot;),<br>              let certData = try? Data(contentsOf: URL(fileURLWithPath: certPath)),<br>              let certificate = SecCertificateCreateWithData(nil, certData as CFData) else {<br>            return nil<br>        }<br>        <br>        return SecCertificateCopyKey(certificate)<br>    }<br>}<br>// Certificate Pinning (Alternative)<br>class CertificatePinning {<br>    func urlSession(<br>        _ session: URLSession,<br>        didReceive challenge: URLAuthenticationChallenge,<br>        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void<br>    ) {<br>        guard let serverTrust = challenge.protectionSpace.serverTrust,<br>              let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br>        <br>        let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data<br>        <br>        // Load pinned certificate<br>        guard let pinnedCertPath = Bundle.main.path(forResource: &quot;certificate&quot;, ofType: &quot;cer&quot;),<br>              let pinnedCertData = try? Data(contentsOf: URL(fileURLWithPath: pinnedCertPath)) else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br>        <br>        if serverCertificateData == pinnedCertData {<br>            let credential = URLCredential(trust: serverTrust)<br>            completionHandler(.useCredential, credential)<br>        } else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>        }<br>    }<br>}</pre><h3>Generate Certificate for SSL Pinning</h3><pre># 1. Download certificate from server<br>openssl s_client -connect api.example.com:443 -showcerts &lt; /dev/null | openssl x509 -outform DER &gt; certificate.cer</pre><pre># 2. Extract public key from certificate<br>openssl x509 -in certificate.cer -inform DER -pubkey -noout &gt; publickey.pem</pre><pre># 3. Get public key hash (for pinning)<br>openssl x509 -in certificate.cer -inform DER -pubkey -noout | \<br>openssl pkey -pubin -outform DER | \<br>openssl dgst -sha256 -binary | \<br>openssl enc -base64</pre><pre># Add .cer file to Xcode project<br># Then use in code as shown above</pre><h3>Private Key Storage</h3><p><strong>Who stores the private key?</strong> The server stores the private key. The client (iOS app) stores the public key or certificate for verification.</p><p><strong>Why?</strong> Private keys are used for decryption and signing. If compromised on client-side, the entire security is broken. Public keys can only verify signatures and encrypt data (which only the server can decrypt).</p><h3>.p12 and .p8 Files</h3><ul><li><strong>.p12 (PKCS#12):</strong> Contains private key + certificate. Used for APNs authentication (older method), code signing. Password-protected.</li><li><strong>.p8:</strong> Contains only the private key. Used for APNs token-based authentication (newer, recommended). Lighter, doesn’t expire.</li></ul><h3>HMAC (Hash-based Message Authentication Code)</h3><p>A method to verify data integrity and authenticity using a secret key + hash function.</p><pre>import CommonCrypto<br><br>extension Data {<br>    func hmacSHA256(key: Data) -&gt; Data {<br>        var hmac = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))<br>        <br>        self.withUnsafeBytes { dataBytes in<br>            key.withUnsafeBytes { keyBytes in<br>                CCHmac(<br>                    CCHmacAlgorithm(kCCHmacAlgSHA256),<br>                    keyBytes.baseAddress,<br>                    key.count,<br>                    dataBytes.baseAddress,<br>                    self.count,<br>                    &amp;hmac<br>                )<br>            }<br>        }<br>        <br>        return Data(hmac)<br>    }<br>}<br>// Usage<br>let message = &quot;Hello, World!&quot;.data(using: .utf8)!<br>let key = &quot;secret-key&quot;.data(using: .utf8)!<br>let signature = message.hmacSHA256(key: key)<br>print(signature.base64EncodedString())</pre><h3>Symmetric vs Asymmetric Encryption</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gV7gStmpUebw1JwxrbIUQ.png" /></figure><pre>import CryptoKit<br>// Symmetric Encryption (AES)<br>func encryptAES(data: Data, key: SymmetricKey) throws -&gt; Data {<br>    let sealedBox = try AES.GCM.seal(data, using: key)<br>    return sealedBox.combined!<br>}<br>func decryptAES(encryptedData: Data, key: SymmetricKey) throws -&gt; Data {<br>    let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)<br>    return try AES.GCM.open(sealedBox, using: key)<br>}<br>// Usage<br>let key = SymmetricKey(size: .bits256)<br>let message = &quot;Secret Message&quot;.data(using: .utf8)!<br>let encrypted = try encryptAES(data: message, key: key)<br>let decrypted = try decryptAES(encryptedData: encrypted, key: key)<br>// Asymmetric Encryption (RSA)<br>func generateRSAKeyPair() -&gt; (publicKey: SecKey, privateKey: SecKey)? {<br>    let attributes: [String: Any] = [<br>        kSecAttrKeyType as String: kSecAttrKeyTypeRSA,<br>        kSecAttrKeySizeInBits as String: 2048<br>    ]<br>    <br>    var error: Unmanaged?<br>    guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &amp;error) else {<br>        return nil<br>    }<br>    <br>    guard let publicKey = SecKeyCopyPublicKey(privateKey) else {<br>        return nil<br>    }<br>    <br>    return (publicKey, privateKey)<br>}<br>func encryptRSA(data: Data, publicKey: SecKey) -&gt; Data? {<br>    var error: Unmanaged?<br>    guard let encrypted = SecKeyCreateEncryptedData(<br>        publicKey,<br>        .rsaEncryptionOAEPSHA256,<br>        data as CFData,<br>        &amp;error<br>    ) else {<br>        return nil<br>    }<br>    <br>    return encrypted as Data<br>}<br>func decryptRSA(encryptedData: Data, privateKey: SecKey) -&gt; Data? {<br>    var error: Unmanaged?<br>    guard let decrypted = SecKeyCreateDecryptedData(<br>        privateKey,<br>        .rsaEncryptionOAEPSHA256,<br>        encryptedData as CFData,<br>        &amp;error<br>    ) else {<br>        return nil<br>    }<br>    <br>    return decrypted as Data<br>}</pre><h3>Key Management</h3><p>The practice of securely generating, storing, distributing, and destroying cryptographic keys.</p><pre>import Security<br><br>class KeychainManager {<br>    <br>    // Store key in Keychain<br>    static func saveKey(_ key: Data, identifier: String) -&gt; Bool {<br>        let query: [String: Any] = [<br>            kSecClass as String: kSecClassGenericPassword,<br>            kSecAttrAccount as String: identifier,<br>            kSecValueData as String: key,<br>            kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly<br>        ]<br>        <br>        SecItemDelete(query as CFDictionary)  // Delete existing<br>        <br>        let status = SecItemAdd(query as CFDictionary, nil)<br>        return status == errSecSuccess<br>    }<br>    <br>    // Retrieve key from Keychain<br>    static func retrieveKey(identifier: String) -&gt; Data? {<br>        let query: [String: Any] = [<br>            kSecClass as String: kSecClassGenericPassword,<br>            kSecAttrAccount as String: identifier,<br>            kSecReturnData as String: true<br>        ]<br>        <br>        var result: AnyObject?<br>        let status = SecItemCopyMatching(query as CFDictionary, &amp;result)<br>        <br>        guard status == errSecSuccess else { return nil }<br>        return result as? Data<br>    }<br>    <br>    // Delete key<br>    static func deleteKey(identifier: String) -&gt; Bool {<br>        let query: [String: Any] = [<br>            kSecClass as String: kSecClassGenericPassword,<br>            kSecAttrAccount as String: identifier<br>        ]<br>        <br>        let status = SecItemDelete(query as CFDictionary)<br>        return status == errSecSuccess<br>    }<br>}<br>// Usage<br>let key = SymmetricKey(size: .bits256)<br>let keyData = key.withUnsafeBytes { Data($0) }<br>KeychainManager.saveKey(keyData, identifier: &quot;encryption_key&quot;)<br>if let retrievedKey = KeychainManager.retrieveKey(identifier: &quot;encryption_key&quot;) {<br>    print(&quot;Key retrieved successfully&quot;)<br>}</pre><h3>Code Obfuscation</h3><p>Making code difficult to reverse-engineer by transforming it while preserving functionality.</p><p><strong>Tools:</strong></p><ul><li><strong>Obfuscator-iOS:</strong> String and class name obfuscation</li><li><strong>o-mvll:</strong> LLVM-based obfuscation (control flow, constants)</li><li><strong>GuardSquare (iXGuard):</strong> Commercial-grade obfuscation</li></ul><pre>// Before obfuscation<br>class LoginManager {<br>    let apiKey = &quot;abc123xyz&quot;<br>    <br>    func login(username: String, password: String) {<br>        // Authentication logic<br>    }<br>}</pre><pre>// After obfuscation (conceptual)<br>class a1b2c3 {<br>    let d4e5f6 = String([97, 98, 99, 49, 50, 51, 120, 121, 122].map { Character(UnicodeScalar($0)) })<br>    <br>    func g7h8i9(j0k1l2: String, m3n4o5: String) {<br>        // Same logic, different symbols<br>    }<br>}</pre><p><strong>Note:</strong> Obfuscation is not encryption. Determined attackers can still reverse-engineer obfuscated code. Use it as one layer in defense-in-depth strategy.</p><h3>5. Swift Language &amp; Core Concepts</h3><h3>Structs as Value Types</h3><p>Structs are copied when assigned or passed to functions. Each copy is independent.</p><pre>struct Point {<br>    var x: Int<br>    var y: Int<br>}</pre><pre>var point1 = Point(x: 10, y: 20)<br>var point2 = point1  // Copy created</pre><pre>point2.x = 30</pre><pre>print(point1.x)  // 10 (unchanged)<br>print(point2.x)  // 30 (modified copy)</pre><pre>// Class (Reference Type) - different behavior<br>class PointClass {<br>    var x: Int<br>    var y: Int<br>    <br>    init(x: Int, y: Int) {<br>        self.x = x<br>        self.y = y<br>    }<br>}</pre><pre>var pointObj1 = PointClass(x: 10, y: 20)<br>var pointObj2 = pointObj1  // Same reference</pre><pre>pointObj2.x = 30</pre><pre>print(pointObj1.x)  // 30 (both changed)<br>print(pointObj2.x)  // 30</pre><h3>GCD, Sync, Async, Serial Queues</h3><pre>import Foundation<br><br>// Serial Queue - Tasks execute one at a time<br>let serialQueue = DispatchQueue(label: &quot;com.example.serial&quot;)<br>serialQueue.async {<br>    print(&quot;Task 1&quot;)<br>}<br>serialQueue.async {<br>    print(&quot;Task 2&quot;)  // Waits for Task 1<br>}<br>// Concurrent Queue - Tasks can execute simultaneously<br>let concurrentQueue = DispatchQueue(label: &quot;com.example.concurrent&quot;, attributes: .concurrent)<br>concurrentQueue.async {<br>    print(&quot;Task A&quot;)<br>}<br>concurrentQueue.async {<br>    print(&quot;Task B&quot;)  // Can run alongside Task A<br>}<br>// Main Queue (Serial)<br>DispatchQueue.main.async {<br>    // UI updates must be on main thread<br>    print(&quot;Update UI&quot;)<br>}<br>// Global Queue (Concurrent)<br>DispatchQueue.global(qos: .background).async {<br>    // Background work<br>    print(&quot;Heavy computation&quot;)<br>    <br>    DispatchQueue.main.async {<br>        // Update UI with results<br>        print(&quot;Show results&quot;)<br>    }<br>}<br>// Sync vs Async<br>serialQueue.sync {<br>    print(&quot;Blocks current thread until complete&quot;)<br>}<br>serialQueue.async {<br>    print(&quot;Doesn&#39;t block, returns immediately&quot;)<br>}<br>// ⚠️ Never call sync on main queue from main thread - DEADLOCK<br>// DispatchQueue.main.sync { }  // ❌ CRASH<br>// DispatchGroup - Wait for multiple tasks<br>let group = DispatchGroup()<br>group.enter()<br>concurrentQueue.async {<br>    print(&quot;Download 1&quot;)<br>    group.leave()<br>}<br>group.enter()<br>concurrentQueue.async {<br>    print(&quot;Download 2&quot;)<br>    group.leave()<br>}<br>group.notify(queue: .main) {<br>    print(&quot;All downloads complete&quot;)<br>}<br>// OperationQueue<br>let operationQueue = OperationQueue()<br>operationQueue.maxConcurrentOperationCount = 2<br>let operation1 = BlockOperation {<br>    print(&quot;Operation 1&quot;)<br>}<br>let operation2 = BlockOperation {<br>    print(&quot;Operation 2&quot;)<br>}<br>operation2.addDependency(operation1)  // operation2 waits for operation1<br>operationQueue.addOperations([operation1, operation2], waitUntilFinished: false)</pre><h3>Custom ForEach without for-in</h3><pre>extension Array {<br>    func customForEach(_ body: (Element) -&gt; Void) {<br>        var index = 0<br>        <br>        func iterate() {<br>            guard index &lt; self.count else { return }<br>            body(self[index])<br>            index += 1<br>            iterate()  // Recursive call<br>        }<br>        <br>        iterate()<br>    }<br>}</pre><pre>// Usage<br>let numbers = [1, 2, 3, 4, 5]<br>numbers.customForEach { print($0) }</pre><pre>// Alternative using while<br>extension Array {<br>    func customForEach2(_ body: (Element) -&gt; Void) {<br>        var index = 0<br>        while index &lt; count {<br>            body(self[index])<br>            index += 1<br>        }<br>    }<br>}</pre><h3>Closures</h3><p>Self-contained blocks of functionality that can be passed around and used in your code.</p><pre>// Basic closure syntax<br>let greeting: (String) -&gt; String = { name in<br>    return &quot;Hello, \(name)!&quot;<br>}</pre><pre>print(greeting(&quot;Alice&quot;))  // &quot;Hello, Alice!&quot;</pre><pre>// Closure as function parameter<br>func performOperation(a: Int, b: Int, operation: (Int, Int) -&gt; Int) -&gt; Int {<br>    return operation(a, b)<br>}</pre><pre>let result = performOperation(a: 5, b: 3, operation: { $0 + $1 })<br>print(result)  // 8</pre><pre>// Trailing closure syntax<br>let result2 = performOperation(a: 5, b: 3) { $0 * $1 }<br>print(result2)  // 15</pre><pre>// Capturing values<br>func makeIncrementer(incrementAmount: Int) -&gt; () -&gt; Int {<br>    var total = 0<br>    <br>    let incrementer: () -&gt; Int = {<br>        total += incrementAmount<br>        return total<br>    }<br>    <br>    return incrementer<br>}</pre><pre>let incrementByTwo = makeIncrementer(incrementAmount: 2)<br>print(incrementByTwo())  // 2<br>print(incrementByTwo())  // 4<br>print(incrementByTwo())  // 6</pre><pre>// Escaping closures<br>class NetworkManager {<br>    var completionHandlers: [() -&gt; Void] = []<br>    <br>    func fetchData(completion: @escaping () -&gt; Void) {<br>        // Closure escapes function scope<br>        completionHandlers.append(completion)<br>    }<br>}</pre><h3>Autoclosure</h3><p>Automatically wraps an expression in a closure, delaying its evaluation.</p><pre>// Without @autoclosure<br>func logIfTrue(_ condition: () -&gt; Bool, message: String) {<br>    if condition() {<br>        print(message)<br>    }<br>}</pre><pre>logIfTrue({ 2 &gt; 1 }, message: &quot;Math works!&quot;)  // Need closure syntax</pre><pre>// With @autoclosure<br>func logIfTrue(_ condition: @autoclosure () -&gt; Bool, message: String) {<br>    if condition() {<br>        print(message)<br>    }<br>}</pre><pre>logIfTrue(2 &gt; 1, message: &quot;Math works!&quot;)  // Cleaner syntax</pre><pre>// Real-world example: Assert<br>func customAssert(_ condition: @autoclosure () -&gt; Bool, _ message: String) {<br>    #if DEBUG<br>    if !condition() {<br>        print(&quot;Assertion failed: \(message)&quot;)<br>    }<br>    #endif<br>}</pre><pre>customAssert(5 &gt; 10, &quot;Five should be greater than ten&quot;)</pre><pre>// Short-circuit evaluation example<br>func &amp;&amp;(lhs: Bool, rhs: @autoclosure () -&gt; Bool) -&gt; Bool {<br>    return lhs ? rhs() : false  // rhs only evaluated if lhs is true<br>}</pre><h3>Protocols and Delegates</h3><pre>// Protocol definition<br>protocol DataSourceDelegate: AnyObject {<br>    func didReceiveData(_ data: String)<br>    func didFailWithError(_ error: Error)<br>}</pre><pre>class DataFetcher {<br>    weak var delegate: DataSourceDelegate?<br>    <br>    func fetchData() {<br>        // Simulate network call<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>            self.delegate?.didReceiveData(&quot;Sample data&quot;)<br>        }<br>    }<br>}</pre><pre>class ViewController: DataSourceDelegate {<br>    let dataFetcher = DataFetcher()<br>    <br>    func setup() {<br>        dataFetcher.delegate = self<br>        dataFetcher.fetchData()<br>    }<br>    <br>    func didReceiveData(_ data: String) {<br>        print(&quot;Received: \(data)&quot;)<br>    }<br>    <br>    func didFailWithError(_ error: Error) {<br>        print(&quot;Error: \(error)&quot;)<br>    }<br>}</pre><pre>// Protocol with associated type<br>protocol Container {<br>    associatedtype Item<br>    var items: [Item] { get set }<br>    mutating func add(_ item: Item)<br>}</pre><pre>struct IntContainer: Container {<br>    var items: [Int] = []<br>    <br>    mutating func add(_ item: Int) {<br>        items.append(item)<br>    }<br>}</pre><pre>// Protocol extensions<br>protocol Greetable {<br>    var name: String { get }<br>    func greet() -&gt; String<br>}</pre><pre>extension Greetable {<br>    func greet() -&gt; String {<br>        return &quot;Hello, \(name)!&quot;<br>    }<br>}</pre><pre>struct Person: Greetable {<br>    let name: String<br>    // greet() provided by extension<br>}</pre><pre>let person = Person(name: &quot;John&quot;)<br>print(person.greet())  // &quot;Hello, John!&quot;</pre><h3>Extensions</h3><pre>// Add computed properties<br>extension Int {<br>    var squared: Int {<br>        return self * self<br>    }<br>    <br>    var isEven: Bool {<br>        return self % 2 == 0<br>    }<br>}</pre><pre>print(5.squared)  // 25<br>print(4.isEven)   // true</pre><pre>// Add methods<br>extension String {<br>    func trimmed() -&gt; String {<br>        return self.trimmingCharacters(in: .whitespaces)<br>    }<br>    <br>    func isPalindrome() -&gt; Bool {<br>        let cleaned = self.lowercased().filter { $0.isLetter }<br>        return cleaned == String(cleaned.reversed())<br>    }<br>}</pre><pre>print(&quot;  Hello  &quot;.trimmed())  // &quot;Hello&quot;<br>print(&quot;racecar&quot;.isPalindrome())  // true</pre><pre>// Add initializers<br>extension UIColor {<br>    convenience init(hex: String) {<br>        var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)<br>        hexSanitized = hexSanitized.replacingOccurrences(of: &quot;#&quot;, with: &quot;&quot;)<br>        <br>        var rgb: UInt64 = 0<br>        Scanner(string: hexSanitized).scanHexInt64(&amp;rgb)<br>        <br>        let r = CGFloat((rgb &amp; 0xFF0000) &gt;&gt; 16) / 255.0<br>        let g = CGFloat((rgb &amp; 0x00FF00) &gt;&gt; 8) / 255.0<br>        let b = CGFloat(rgb &amp; 0x0000FF) / 255.0<br>        <br>        self.init(red: r, green: g, blue: b, alpha: 1.0)<br>    }<br>}</pre><pre>let color = UIColor(hex: &quot;#FF5733&quot;)</pre><pre>// Protocol conformance<br>extension Array: Greetable where Element == String {<br>    var name: String {<br>        return self.joined(separator: &quot;, &quot;)<br>    }<br>}</pre><h3>Optionals</h3><pre>// Optional binding<br>var name: String? = &quot;Alice&quot;</pre><pre>if let unwrappedName = name {<br>    print(&quot;Hello, \(unwrappedName)&quot;)<br>} else {<br>    print(&quot;Name is nil&quot;)<br>}</pre><pre>// Guard let (early exit)<br>func greet(person: String?) {<br>    guard let name = person else {<br>        print(&quot;No name provided&quot;)<br>        return<br>    }<br>    print(&quot;Hello, \(name)&quot;)<br>}</pre><pre>// Nil coalescing<br>let userName = name ?? &quot;Guest&quot;</pre><pre>// Optional chaining<br>class Address {<br>    var street: String?<br>}</pre><pre>class Person {<br>    var address: Address?<br>}</pre><pre>let person: Person? = Person()<br>let street = person?.address?.street  // nil if any step is nil</pre><pre>// Force unwrapping (use carefully)<br>let definitelyHasValue: String? = &quot;Value&quot;<br>print(definitelyHasValue!)  // ⚠️ Crashes if nil</pre><pre>// Implicitly unwrapped optionals<br>var assumedString: String! = &quot;Hello&quot;<br>print(assumedString)  // Auto-unwrapped</pre><pre>// Optional map and flatMap<br>let number: Int? = 5<br>let doubled = number.map { $0 * 2 }  // Optional(10)</pre><pre>let nestedOptional: Int?? = 5<br>let flattened = nestedOptional.flatMap { $0 }  // Optional(5)</pre><h3>Initializers</h3><pre>class Vehicle {<br>    var brand: String<br>    var model: String<br>    <br>    // Designated initializer<br>    init(brand: String, model: String) {<br>        self.brand = brand<br>        self.model = model<br>    }<br>    <br>    // Convenience initializer<br>    convenience init(brand: String) {<br>        self.init(brand: brand, model: &quot;Unknown&quot;)<br>    }<br>    <br>    // Convenience with default values<br>    convenience init() {<br>        self.init(brand: &quot;Generic&quot;, model: &quot;Generic&quot;)<br>    }<br>}</pre><pre>let car1 = Vehicle(brand: &quot;Toyota&quot;, model: &quot;Camry&quot;)<br>let car2 = Vehicle(brand: &quot;Honda&quot;)  // model = &quot;Unknown&quot;<br>let car3 = Vehicle()  // brand and model = &quot;Generic&quot;</pre><pre>// Failable initializer<br>struct Temperature {<br>    var celsius: Double<br>    <br>    init?(celsius: Double) {<br>        guard celsius &gt;= -273.15 else {<br>            return nil  // Absolute zero limit<br>        }<br>        self.celsius = celsius<br>    }<br>}</pre><pre>let temp = Temperature(celsius: -300)  // nil</pre><pre>// Required initializer (in subclasses)<br>class Parent {<br>    required init() {<br>        // Must be implemented by all subclasses<br>    }<br>}</pre><pre>class Child: Parent {<br>    required init() {<br>        super.init()<br>    }<br>}</pre><h3>Property Wrappers</h3><pre>// Built-in property wrappers in SwiftUI<br>@State private var count = 0<br>@Binding var isPresented: Bool<br>@Published var username: String<br>@ObservedObject var viewModel: ViewModel<br>@StateObject var manager = NetworkManager()<br>@Environment(\.colorScheme) var colorScheme<br>@AppStorage(&quot;theme&quot;) var theme: String = &quot;light&quot;</pre><pre>// Custom property wrapper<br>@propertyWrapper<br>struct Capitalized {<br>    private var value: String = &quot;&quot;<br>    <br>    var wrappedValue: String {<br>        get { value }<br>        set { value = newValue.capitalized }<br>    }<br>    <br>    init(wrappedValue: String) {<br>        self.value = wrappedValue.capitalized<br>    }<br>}</pre><pre>struct User {<br>    @Capitalized var firstName: String<br>    @Capitalized var lastName: String<br>}</pre><pre>var user = User(firstName: &quot;john&quot;, lastName: &quot;doe&quot;)<br>print(user.firstName)  // &quot;John&quot;</pre><pre>// Property wrapper with constraints<br>@propertyWrapper<br>struct Clamped {<br>    private var value: Value<br>    private let range: ClosedRange<br>    <br>    var wrappedValue: Value {<br>        get { value }<br>        set { value = min(max(newValue, range.lowerBound), range.upperBound) }<br>    }<br>    <br>    init(wrappedValue: Value, _ range: ClosedRange) {<br>        self.range = range<br>        self.value = min(max(wrappedValue, range.lowerBound), range.upperBound)<br>    }<br>}</pre><pre>struct Game {<br>    @Clamped(0...100) var health: Int = 100<br>}</pre><pre>var game = Game()<br>game.health = 150<br>print(game.health)  // 100 (clamped)</pre><pre>game.health = -10<br>print(game.health)  // 0 (clamped)</pre><h3>Actors</h3><p>Reference types that protect their mutable state from data races.</p><pre>// Actor for thread-safe data access<br>actor BankAccount {<br>    private var balance: Double = 0<br>    <br>    func deposit(amount: Double) {<br>        balance += amount<br>    }<br>    <br>    func withdraw(amount: Double) -&gt; Bool {<br>        guard balance &gt;= amount else {<br>            return false<br>        }<br>        balance -= amount<br>        return true<br>    }<br>    <br>    func getBalance() -&gt; Double {<br>        return balance<br>    }<br>}</pre><pre>// Usage (must use await)<br>Task {<br>    let account = BankAccount()<br>    await account.deposit(amount: 100)<br>    <br>    let balance = await account.getBalance()<br>    print(&quot;Balance: $\(balance)&quot;)<br>    <br>    let success = await account.withdraw(amount: 50)<br>    print(&quot;Withdrawal: \(success)&quot;)<br>}</pre><pre>// @MainActor for main thread execution<br>@MainActor<br>class ViewModel: ObservableObject {<br>    @Published var users: [User] = []<br>    <br>    func loadUsers() async {<br>        // Automatically runs on main thread<br>        users = await fetchUsersFromAPI()<br>    }<br>}</pre><pre>// Global actor<br>@globalActor<br>struct DatabaseActor {<br>    actor ActorType { }<br>    static let shared = ActorType()<br>}</pre><pre>@DatabaseActor<br>class DatabaseManager {<br>    func saveData(_ data: Data) {<br>        // Protected by DatabaseActor<br>    }<br>}</pre><h3>Higher-Order Functions</h3><pre>let numbers = [1, 2, 3, 4, 5, 6]</pre><pre>// Map - Transform each element<br>let doubled = numbers.map { $0 * 2 }<br>print(doubled)  // [2, 4, 6, 8, 10, 12]</pre><pre>// Filter - Select elements matching condition<br>let evens = numbers.filter { $0 % 2 == 0 }<br>print(evens)  // [2, 4, 6]</pre><pre>// Reduce - Combine all elements into single value<br>let sum = numbers.reduce(0, +)<br>print(sum)  // 21</pre><pre>let product = numbers.reduce(1, *)<br>print(product)  // 720</pre><pre>// CompactMap - Transform and remove nils<br>let strings = [&quot;1&quot;, &quot;2&quot;, &quot;abc&quot;, &quot;3&quot;, &quot;4&quot;]<br>let validNumbers = strings.compactMap { Int($0) }<br>print(validNumbers)  // [1, 2, 3, 4]</pre><pre>// FlatMap - Flatten nested arrays<br>let nestedArrays = [[1, 2], [3, 4], [5, 6]]<br>let flattened = nestedArrays.flatMap { $0 }<br>print(flattened)  // [1, 2, 3, 4, 5, 6]</pre><pre>// ForEach - Execute closure for each element<br>numbers.forEach { print($0) }</pre><pre>// Chaining<br>let result = numbers<br>    .filter { $0 % 2 == 0 }<br>    .map { $0 * 2 }<br>    .reduce(0, +)<br>print(result)  // 24</pre><pre>// Custom higher-order function<br>func apply(_ value: T, _ transform: (T) -&gt; T) -&gt; T {<br>    return transform(value)<br>}</pre><pre>let tripled = apply(5) { $0 * 3 }<br>print(tripled)  // 15</pre><pre>// Sorted<br>let unsorted = [5, 2, 8, 1, 9]<br>let sorted = unsorted.sorted()<br>print(sorted)  // [1, 2, 5, 8, 9]</pre><pre>let sortedDesc = unsorted.sorted { $0 &gt; $1 }<br>print(sortedDesc)  // [9, 8, 5, 2, 1]</pre><h3>6. Testing</h3><h3>Snapshot Testing</h3><p>Captures the UI state as an image/JSON and compares it with a reference in future tests. Catches unintended visual regressions.</p><pre>import XCTest<br>import SnapshotTesting  // Library: pointfreeco/swift-snapshot-testing</pre><pre>class ViewControllerTests: XCTestCase {<br>    <br>    func testHomeViewSnapshot() {<br>        let vc = HomeViewController()<br>        <br>        // First run: generates reference image<br>        // Subsequent runs: compares with reference<br>        assertSnapshot(matching: vc, as: .image)<br>    }<br>    <br>    func testSwiftUIViewSnapshot() {<br>        let view = ContentView()<br>        assertSnapshot(matching: view, as: .image)<br>    }<br>    <br>    func testDarkModeSnapshot() {<br>        let vc = ProfileViewController()<br>        vc.overrideUserInterfaceStyle = .dark<br>        <br>        assertSnapshot(matching: vc, as: .image)<br>    }<br>}</pre><pre>// Update snapshots when intentionally changed<br>// Run with: swift test --snapshot-testing-update-snapshots</pre><h3>Stub vs Mock</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwzuMNVu-BCPvx_0oX8jaA.png" /></figure><pre>// Protocol<br>protocol UserServiceProtocol {<br>    func fetchUser(id: String) async throws -&gt; User<br>}</pre><pre>// Stub - Returns canned responses<br>class UserServiceStub: UserServiceProtocol {<br>    var userToReturn: User?<br>    var errorToThrow: Error?<br>    <br>    func fetchUser(id: String) async throws -&gt; User {<br>        if let error = errorToThrow {<br>            throw error<br>        }<br>        return userToReturn ?? User(id: &quot;1&quot;, name: &quot;Default&quot;)<br>    }<br>}</pre><pre>// Mock - Verifies interactions<br>class UserServiceMock: UserServiceProtocol {<br>    var fetchUserCalled = false<br>    var fetchUserCallCount = 0<br>    var fetchUserCalledWithId: String?<br>    var userToReturn: User?<br>    <br>    func fetchUser(id: String) async throws -&gt; User {<br>        fetchUserCalled = true<br>        fetchUserCallCount += 1<br>        fetchUserCalledWithId = id<br>        <br>        return userToReturn ?? User(id: id, name: &quot;Mock User&quot;)<br>    }<br>}</pre><pre>// Usage in tests<br>class ViewModelTests: XCTestCase {<br>    <br>    func testLoadUserWithStub() async {<br>        // Stub - focus on state/output<br>        let stub = UserServiceStub()<br>        stub.userToReturn = User(id: &quot;123&quot;, name: &quot;Alice&quot;)<br>        <br>        let viewModel = UserViewModel(userService: stub)<br>        await viewModel.loadUser(id: &quot;123&quot;)<br>        <br>        XCTAssertEqual(viewModel.userName, &quot;Alice&quot;)<br>    }<br>    <br>    func testLoadUserWithMock() async {<br>        // Mock - focus on behavior/interactions<br>        let mock = UserServiceMock()<br>        mock.userToReturn = User(id: &quot;123&quot;, name: &quot;Bob&quot;)<br>        <br>        let viewModel = UserViewModel(userService: mock)<br>        await viewModel.loadUser(id: &quot;123&quot;)<br>        <br>        // Verify behavior<br>        XCTAssertTrue(mock.fetchUserCalled)<br>        XCTAssertEqual(mock.fetchUserCallCount, 1)<br>        XCTAssertEqual(mock.fetchUserCalledWithId, &quot;123&quot;)<br>    }<br>}</pre><h3>100% Test Coverage</h3><p><strong>Steps:</strong></p><ol><li>Write unit tests for all business logic (ViewModels, Use Cases, Repositories)</li><li>Use dependency injection to make code testable</li><li>Test all code paths (if/else, switch cases, error handling)</li><li>Enable code coverage in Xcode (Edit Scheme → Test → Options → Code Coverage)</li><li>Review coverage report (Report Navigator → Coverage)</li><li>Write tests for uncovered lines</li></ol><pre>// Testable ViewModel with DI<br>class UserViewModel {<br>    private let userService: UserServiceProtocol<br>    @Published var userName: String = &quot;&quot;<br>    @Published var errorMessage: String?<br>    <br>    init(userService: UserServiceProtocol) {<br>        self.userService = userService<br>    }<br>    <br>    func loadUser(id: String) async {<br>        do {<br>            let user = try await userService.fetchUser(id: id)<br>            userName = user.name<br>            errorMessage = nil<br>        } catch {<br>            errorMessage = error.localizedDescription<br>        }<br>    }<br>}</pre><pre>// Comprehensive test<br>class UserViewModelTests: XCTestCase {<br>    <br>    func testLoadUserSuccess() async {<br>        let mock = UserServiceMock()<br>        mock.userToReturn = User(id: &quot;1&quot;, name: &quot;Alice&quot;)<br>        <br>        let viewModel = UserViewModel(userService: mock)<br>        await viewModel.loadUser(id: &quot;1&quot;)<br>        <br>        XCTAssertEqual(viewModel.userName, &quot;Alice&quot;)<br>        XCTAssertNil(viewModel.errorMessage)<br>    }<br>    <br>    func testLoadUserFailure() async {<br>        let mock = UserServiceMock()<br>        mock.errorToThrow = NSError(domain: &quot;Test&quot;, code: 404)<br>        <br>        let viewModel = UserViewModel(userService: mock)<br>        await viewModel.loadUser(id: &quot;1&quot;)<br>        <br>        XCTAssertEqual(viewModel.userName, &quot;&quot;)<br>        XCTAssertNotNil(viewModel.errorMessage)<br>    }<br>}</pre><h3>CI/CD Integration</h3><p><strong>Tools:</strong> GitHub Actions, GitLab CI, Bitrise, Xcode Cloud, Jenkins</p><pre># GitHub Actions example (.github/workflows/ios.yml)<br>name: iOS CI<br><br>on:<br>  push:<br>    branches: [ main, develop ]<br>  pull_request:<br>    branches: [ main, develop ]<br>jobs:<br>  build-and-test:<br>    runs-on: macos-latest<br>    <br>    steps:<br>    - uses: actions/checkout@v3<br>    <br>    - name: Set up Xcode<br>      uses: maxim-lobanov/setup-xcode@v1<br>      with:<br>        xcode-version: &#39;15.0&#39;<br>    <br>    - name: Install dependencies<br>      run: |<br>        pod install<br>    <br>    - name: Build<br>      run: |<br>        xcodebuild clean build \<br>          -workspace MyApp.xcworkspace \<br>          -scheme MyApp \<br>          -destination &#39;platform=iOS Simulator,name=iPhone 14&#39;<br>    <br>    - name: Run tests<br>      run: |<br>        xcodebuild test \<br>          -workspace MyApp.xcworkspace \<br>          -scheme MyApp \<br>          -destination &#39;platform=iOS Simulator,name=iPhone 14&#39; \<br>          -enableCodeCoverage YES<br>    <br>    - name: Upload coverage<br>      uses: codecov/codecov-action@v3<br>      with:<br>        files: ./coverage.xml<br>    <br>    - name: Archive build artifacts<br>      uses: actions/upload-artifact@v3<br>      with:<br>        name: build-artifacts<br>        path: build/</pre><h3>7. Scenario-Based / Behavioral</h3><h3>Handling Unclear Requirements</h3><p><strong>Answer:</strong></p><ol><li><strong>Ask clarifying questions:</strong> “What’s the expected behavior when X happens?”</li><li><strong>Document assumptions:</strong> Write down what you’re assuming and get confirmation</li><li><strong>Create prototypes:</strong> Build quick mockups to validate understanding</li><li><strong>Break into smaller tasks:</strong> Identify what’s clear and start there</li><li><strong>Regular check-ins:</strong> Show progress frequently to catch misunderstandings early</li></ol><p><strong>Example:</strong> “The requirement says ‘user-friendly interface.’ I need to clarify: Does this mean we need accessibility support (VoiceOver)? What’s the target user demographic? Are there specific UI guidelines we should follow?”</p><h3>Architecture Migration (MVC to MVVM)</h3><p><strong>Approach:</strong></p><ol><li><strong>Incremental migration:</strong> Don’t rewrite everything at once</li><li><strong>Start with new features:</strong> Build new screens in MVVM</li><li><strong>Migrate high-value screens:</strong> Screens with complex logic benefit most</li><li><strong>Create adapters:</strong> Bridge between old and new architecture</li><li><strong>Maintain tests:</strong> Ensure functionality doesn’t break</li></ol><pre>// Step 1: Extract business logic to ViewModel<br>// Before (MVC)<br>class UserViewController: UIViewController {<br>    func loadUser() {<br>        NetworkManager.shared.fetchUser { user in<br>            self.nameLabel.text = user.name<br>            // More logic...<br>        }<br>    }<br>}</pre><pre>// Step 2: Create ViewModel<br>class UserViewModel {<br>    @Published var userName: String = &quot;&quot;<br>    private let userService: UserServiceProtocol<br>    <br>    init(userService: UserServiceProtocol) {<br>        self.userService = userService<br>    }<br>    <br>    func loadUser() async {<br>        let user = try? await userService.fetchUser(id: &quot;123&quot;)<br>        userName = user?.name ?? &quot;&quot;<br>    }<br>}</pre><pre>// Step 3: Update ViewController to use ViewModel<br>class UserViewController: UIViewController {<br>    private let viewModel: UserViewModel<br>    private var cancellables = Set()<br>    <br>    init(viewModel: UserViewModel) {<br>        self.viewModel = viewModel<br>        super.init(nibName: nil, bundle: nil)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bindViewModel()<br>        Task { await viewModel.loadUser() }<br>    }<br>    <br>    private func bindViewModel() {<br>        viewModel.$userName<br>            .assign(to: \.text, on: nameLabel)<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><h3>Handling Certificate Renewal</h3><p><strong>Strategy:</strong></p><ol><li><strong>Use Public Key Pinning:</strong> Allows certificate renewal without app update</li><li><strong>Multiple pins:</strong> Pin both current and next public key</li><li><strong>Fallback mechanism:</strong> Allow temporary bypass with logging for monitoring</li><li><strong>Remote configuration:</strong> Fetch pins from secure server endpoint</li><li><strong>Monitoring:</strong> Alert when pinning failures spike</li></ol><pre>class CertificateManager {<br>    // Pin both old and new public key hashes<br>    private let pinnedKeys = [<br>        &quot;sha256/CURRENT_KEY_HASH&quot;,<br>        &quot;sha256/NEXT_KEY_HASH&quot;  // Add before renewal<br>    ]<br>    <br>    func validateServerTrust(_ serverTrust: SecTrust) -&gt; Bool {<br>        guard let serverKey = SecTrustCopyKey(serverTrust) else {<br>            return false<br>        }<br>        <br>        let serverKeyData = SecKeyCopyExternalRepresentation(serverKey, nil)! as Data<br>        let serverKeyHash = sha256(serverKeyData)<br>        <br>        // Check if server key matches any pinned key<br>        return pinnedKeys.contains(where: { pinnedHash in<br>            return serverKeyHash == pinnedHash<br>        })<br>    }<br>    <br>    private func sha256(_ data: Data) -&gt; String {<br>        var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))<br>        data.withUnsafeBytes {<br>            _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &amp;hash)<br>        }<br>        return Data(hash).base64EncodedString()<br>    }<br>}</pre><h3>8. Tools &amp; Quality</h3><h3>SonarQube and Code Smells</h3><p><strong>SonarQube:</strong> Static code analysis tool that detects bugs, vulnerabilities, and code smells.</p><p><strong>Code Smells:</strong> Indicators of potential problems in code structure/design:</p><ul><li><strong>Long Method:</strong> Functions with too many lines (&gt;30)</li><li><strong>Large Class:</strong> Classes with too many responsibilities</li><li><strong>Duplicated Code:</strong> Copy-pasted logic</li><li><strong>Dead Code:</strong> Unused variables/functions</li><li><strong>Complex Conditions:</strong> Deeply nested if/else</li><li><strong>Magic Numbers:</strong> Hardcoded values without explanation</li></ul><pre>// ❌ Code Smells<br>class UserManager {<br>    func processUser(user: User) {<br>        // Long method (100+ lines)<br>        if user.age &gt; 18 {<br>            if user.hasValidEmail {<br>                if user.isActive {<br>                    // Deep nesting<br>                    if user.balance &gt; 100 {  // Magic number<br>                        // More logic...<br>                    }<br>                }<br>            }<br>        }<br>        // Duplicated code<br>        let formatter = DateFormatter()<br>        formatter.dateStyle = .short<br>        // ... repeated elsewhere<br>    }<br>}</pre><pre>// ✅ Refactored<br>class UserManager {<br>    private let minimumBalance: Double = 100  // Named constant<br>    <br>    func processUser(user: User) {<br>        guard isEligibleUser(user) else { return }<br>        performUserAction(user)<br>    }<br>    <br>    private func isEligibleUser(_ user: User) -&gt; Bool {<br>        return user.age &gt; 18 &amp;&amp;<br>               user.hasValidEmail &amp;&amp;<br>               user.isActive &amp;&amp;<br>               user.balance &gt; minimumBalance<br>    }<br>    <br>    private func performUserAction(_ user: User) {<br>        // Single responsibility<br>    }<br>}</pre><pre>// Shared formatter (DRY principle)<br>extension DateFormatter {<br>    static let shortDate: DateFormatter = {<br>        let formatter = DateFormatter()<br>        formatter.dateStyle = .short<br>        return formatter<br>    }()<br>}</pre><h3>Code Quality and Maintainability</h3><p><strong>Best Practices:</strong></p><ol><li><strong>SOLID Principles:</strong> Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion</li><li><strong>DRY (Don’t Repeat Yourself):</strong> Extract common logic</li><li><strong>KISS (Keep It Simple):</strong> Avoid over-engineering</li><li><strong>Code Reviews:</strong> Peer review all PRs</li><li><strong>Automated Testing:</strong> Unit, Integration, UI tests</li><li><strong>Linting:</strong> SwiftLint for consistent style</li><li><strong>Documentation:</strong> Clear comments and README</li><li><strong>Static Analysis:</strong> SonarQube, Xcode Analyzer</li></ol><pre>// SwiftLint configuration (.swiftlint.yml)<br>disabled_rules:<br>  - trailing_whitespace<br>opt_in_rules:<br>  - empty_count<br>  - closure_spacing<br>included:<br>  - Sources<br>excluded:<br>  - Pods<br>  - Build<br>line_length: 120<br>function_body_length: 40<br>type_body_length: 300</pre><h3>9. DSA / Problem Solving</h3><h3>Check if Two Strings are Anagrams</h3><pre>func areAnagrams(_ str1: String, _ str2: String) -&gt; Bool {<br>    // Method 1: Sorting<br>    let sorted1 = str1.lowercased().sorted()<br>    let sorted2 = str2.lowercased().sorted()<br>    return sorted1 == sorted2<br>}</pre><pre>// Method 2: Character frequency<br>func areAnagrams2(_ str1: String, _ str2: String) -&gt; Bool {<br>    guard str1.count == str2.count else { return false }<br>    <br>    var charCount: [Character: Int] = [:]<br>    <br>    // Count characters in first string<br>    for char in str1.lowercased() {<br>        charCount[char, default: 0] += 1<br>    }<br>    <br>    // Subtract counts for second string<br>    for char in str2.lowercased() {<br>        charCount[char, default: 0] -= 1<br>        if charCount[char]! &lt; 0 {<br>            return false<br>        }<br>    }<br>    <br>    // All counts should be zero<br>    return charCount.values.allSatisfy { $0 == 0 }<br>}</pre><pre>// Method 3: Using Dictionary<br>func areAnagrams3(_ str1: String, _ str2: String) -&gt; Bool {<br>    let freq1 = Dictionary(str1.lowercased().map { ($0, 1) }, uniquingKeysWith: +)<br>    let freq2 = Dictionary(str2.lowercased().map { ($0, 1) }, uniquingKeysWith: +)<br>    return freq1 == freq2<br>}</pre><pre>// Tests<br>print(areAnagrams(&quot;listen&quot;, &quot;silent&quot;))  // true<br>print(areAnagrams(&quot;hello&quot;, &quot;world&quot;))    // false<br>print(areAnagrams(&quot;Dormitory&quot;, &quot;Dirty room&quot;))  // true (ignoring spaces)</pre><p><strong>Time Complexity:</strong></p><ul><li>Method 1 (Sorting): O(n log n)</li><li>Method 2 (Frequency): O(n)</li><li>Method 3 (Dictionary): O(n)</li></ul><h3>10. Agile &amp; Methodology</h3><h3>Agile Methodology</h3><p><strong>Agile:</strong> Iterative software development approach emphasizing flexibility, collaboration, and customer feedback.</p><p><strong>Key Principles:</strong></p><ul><li>Deliver working software frequently (2–4 weeks)</li><li>Welcome changing requirements</li><li>Collaborate with customers daily</li><li>Self-organizing teams</li><li>Continuous improvement through retrospectives</li></ul><h3>Scrum Terminology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDB4EBk6OBYvwpOPeVFg5g.png" /></figure><h3>Scrum Roles</h3><ul><li><strong>Product Owner:</strong> Defines features, prioritizes backlog, accepts work</li><li><strong>Scrum Master:</strong> Facilitates process, removes blockers, coaches team</li><li><strong>Development Team:</strong> Cross-functional team that delivers product increment</li></ul><h3>Example User Story</h3><p><strong>Story:</strong> As a mobile user, I want to enable biometric login so that I can access the app quickly and securely.</p><p><strong>Acceptance Criteria:</strong></p><ul><li>User can enable Face ID/Touch ID in settings</li><li>Biometric prompt appears on app launch if enabled</li><li>Fallback to PIN if biometric fails</li><li>Setting persists across app restarts</li></ul><p><strong>Story Points:</strong> 5</p><h3>🎯 Interview Preparation Complete!</h3><p>This guide covers all major iOS senior developer topics with code examples.</p><p>Good luck with your interview! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bab91cccfb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing “vapor” (swift server) Framework on Ubuntu 22.04 Server (ARM64) VM for M1 Mac Users]]></title>
            <link>https://medium.com/@iosdevrajesh/installing-vapor-swift-server-framework-on-ubuntu-22-04-server-arm64-vm-for-m1-mac-users-f672166fd948?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/f672166fd948</guid>
            <category><![CDATA[swift-nio]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[m1-mac]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 19:27:56 GMT</pubDate>
            <atom:updated>2023-08-29T16:46:22.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I_7muhto3r65K9zSuXM-w.png" /></figure><p><strong>Introduction</strong>:</p><blockquote><a href="https://vapor.codes/">Vapor</a> is a powerful server-side Swift framework that enables developers to build robust web applications. Non-blocking, event-driven architecture built on top of Apple’s <a href="https://github.com/apple/swift-nio">SwiftNIO</a>. Written in <a href="https://swift.org/">Swift</a>, the powerful programming language. Expressive, <a href="https://developer.apple.com/videos/play/wwdc2015/408/">protocol-oriented</a> design with a focus on type-safety.</blockquote><blockquote>To embark on this journey, it’s essential to first set up the Swift programming language on your <a href="https://cdimage.ubuntu.com/jammy/daily-live/current/jammy-desktop-arm64.iso">Ubuntu 22.04 LTS ARM</a> Server, specifically tailored for ARM64 architecture, which is ideal for M1 Mac users. This step-by-step guide will walk you through the installation process and ensure a smooth setup for Vapor.</blockquote><p><strong>Step 1:</strong></p><p>Checking Swift Version After launching your Ubuntu Virtual Machine on your M1 Mac, open the terminal application and determine the installed Swift version by executing the following command:</p><pre>swift --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5QNK8QSnMLVJhtUzllsVw.png" /></figure><p>If swift not installed, refer my other post about <a href="https://medium.com/@iosdevrajesh/how-to-install-swift-language-on-ubuntu-22-04-lts-vm-on-m1-macbook-pro-4f47cc81e407"><em>how to install swift on Ubuntu 22.04 LTS server</em></a><em>.</em></p><p><strong>Step 2:</strong> Navigating to the Downloads Folder using the following command:</p><pre>cd Downloads</pre><p><strong>Step 3:</strong> Installing Git Before proceeding, ensure that Git is installed. If not, execute the command below to install Git:</p><pre>sudo apt-get install git</pre><p><strong>Step 4:</strong> Clone the Vapor Toolbox repository from GitHub using the following command:</p><pre>git clone https://github.com/vapor/toolbox.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuXRt9XfdYc9YwXZ1Z6F6g.png" /></figure><p><strong>Step 5:</strong> Verify that the repository has been successfully fetched to the Downloads folder by listing the downloaded files:</p><pre>ll</pre><p><strong>Step 6:</strong> Navigate to the ‘toolbox’ directory by entering the following command:</p><pre>cd toolbox</pre><p><strong>Step 7:</strong> Verifying Toolbox Contents List the files within the ‘toolbox’ directory to ensure that all necessary files are present:</p><pre>ll</pre><p><strong>Step 8:</strong> Installing Vapor Toolbox Execute the command below to install the Vapor Toolbox:</p><pre>make install</pre><p><strong>Step 9:</strong> Verifying Vapor Installation After a successful installation by entering the following command:</p><pre>vapor --help</pre><p>This command will display a list of available Vapor commands in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzxAAqMRMuKcOLLFTkgV6A.png" /></figure><p>Congratulations! You have now accomplished the installation of both the Swift programming language and the Vapor framework on your Ubuntu 22.04 Server (ARM64). With Vapor up and running, you are well-equipped to develop powerful and efficient server-side applications. Happy coding!</p><p>Feel free to share your thoughts and questions in the comments section below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f672166fd948" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install “Swift” language on Ubuntu 22.04 LTS VM on M1 MacBook Pro]]></title>
            <link>https://medium.com/@iosdevrajesh/how-to-install-swift-language-on-ubuntu-22-04-lts-vm-on-m1-macbook-pro-4f47cc81e407?source=rss-bff1c5fe0850------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f47cc81e407</guid>
            <category><![CDATA[ubuntu-server]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[m1-macbook-pro]]></category>
            <dc:creator><![CDATA[Rajesh Mani]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 17:56:09 GMT</pubDate>
            <atom:updated>2023-08-29T16:43:58.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ImR2TCVHcuNO05zd2nEHg.png" /></figure><blockquote>The motivation behind this article stems from a personal experience wherein I encountered challenges while attempting to install SwiftLang a dependency to run “<a href="https://vapor.codes/">vapor</a>” server on an <a href="https://cdimage.ubuntu.com/releases/22.04/release/">Ubuntu server</a> Virtual Machine. The server was hosted on a virtual machine using “<a href="https://www.vmware.com/in/products/fusion.html">VMware Fusion</a>” on an M1 Mac. The particular challenge arose from the fact that the majority of tutorials available were geared towards Ubuntu 22.04 on x86_64 architecture, rendering them incompatible with ARM-based machines like the M1 Mac.</blockquote><blockquote>As a result, I felt compelled to address this gap in information and provide a comprehensive guide tailored specifically for ARM architecture installations on M1 Macs.</blockquote><p><strong>Requirements</strong>:</p><p>To successfully install SwiftLang on an ARM64 architecture, such as the one found in Apple M1 Macs, the following prerequisites are necessary:</p><ol><li>An <a href="https://cdimage.ubuntu.com/jammy/daily-live/current/jammy-desktop-arm64.iso">Ubuntu 22.04 LTS (Arm64)</a> installed on a virtual machine application compatible with Apple M1 Macs, such as <a href="https://www.vmware.com/in/products/fusion.html">VMware Fusion</a> (version 13.0.2), <a href="https://mac.getutm.app/">UTM</a>, or <a href="https://www.parallels.com/">Parallels Desktop</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txPUje1O08mCdFS-cRqoFg.png" /></figure><h3><strong>Step-by-Step Installation Guide:</strong></h3><p><strong>Step 1:</strong></p><p>Launch the Ubuntu 22.04 LTS Virtual Machine on Your M1 Mac</p><p>Begin by initiating the Ubuntu 22.04 LTS virtual machine on your M1 Mac. Once the virtual machine is up and running, open the terminal application and execute the following command to update and upgrade your system packages:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade</pre><p><strong>Step 2:</strong></p><p>Execute the below command to install <a href="https://www.swift.org/download/">dependencies</a>.</p><pre>apt-get install \<br>          binutils \<br>          git \<br>          gnupg2 \<br>          libc6-dev \<br>          libcurl4-openssl-dev \<br>          libedit2 \<br>          libgcc-9-dev \<br>          libpython3.8 \<br>          libsqlite3-0 \<br>          libstdc++-9-dev \<br>          libxml2-dev \<br>          libz3-dev \<br>          pkg-config \<br>          tzdata \<br>          unzip \<br>          zlib1g-dev</pre><p><strong>Step 3: Install “curl” (If Not Already Installed)</strong></p><p>If the “curl” utility is not already installed on your system, you can install it using the following command:</p><pre>sudo apt install curl</pre><p><strong>Step 4: SwiftLang Installation</strong></p><p>Use the “curl” command to swiftly install the script required for SwiftLang installation:</p><pre>curl -s https://archive.swiftlang.xyz/install.sh | sudo bash</pre><p>Upon successful execution, you will be presented with a list of available Swift versions. Choose the desired Swift version; for instance, I selected Swift 5.7. If you want install latest stable version select “option 1”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IVKaUM3icn_v45PHKTAgg.png" /></figure><p><strong>Step 5: Install SwiftLang</strong></p><p>Install SwiftLang using the following command:</p><pre>sudo apt install swiftlang</pre><p>Please be patient, as this process may take some time to complete. Once the download and installation are finished, you can verify the successful installation by entering ‘swift’ in the terminal. This will display a list of sub-commands along with a welcoming message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5QNK8QSnMLVJhtUzllsVw.png" /></figure><p>Congratulations! You have now successfully installed SwiftLang on your ARM64 architecture system. You are all set to start utilizing Swift for your programming endeavors. Best of luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f47cc81e407" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>