<?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 Fahad Almehawas on Medium]]></title>
        <description><![CDATA[Stories by Fahad Almehawas on Medium]]></description>
        <link>https://medium.com/@almehawas?source=rss-209e1066ef9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BSepijEFwzGOk3v4ZCkU6w.jpeg</url>
            <title>Stories by Fahad Almehawas on Medium</title>
            <link>https://medium.com/@almehawas?source=rss-209e1066ef9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:46:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@almehawas/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[From Cloud to Chip: The Core ML Revolution]]></title>
            <link>https://medium.com/@almehawas/from-cloud-to-chip-the-core-ml-revolution-f3b11a4a5777?source=rss-209e1066ef9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b11a4a5777</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[coreml]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fahad Almehawas]]></dc:creator>
            <pubDate>Fri, 16 May 2025 06:06:57 GMT</pubDate>
            <atom:updated>2025-05-16T06:22:50.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlZEQ02Jep_07IdOWr5bKA.png" /></figure><p>As machine learning continues its migration from the cloud to the edge, <strong>Core ML</strong> has become Apple’s go-to framework for bringing intelligent features directly onto iPhone, iPad, Mac, and Apple Watch devices. In this post, we’ll explore why Core ML matters, unpack the latest enhancements — especially those unveiled at WWDC24 — and show you how to get started integrating advanced on-device models into your apps.</p><h3>Why Core ML?</h3><p>At its core, Core ML provides a <strong>unified representation</strong> for a wide variety of model types — vision, NLP, sound, and even generative AI — so you don’t have to juggle multiple frameworks or worry about cloud latency. Your app simply uses the Core ML API to load a pre-compiled .mlmodel and make predictions, all while keeping user data private and offline by default. See Apple’s Core ML overview for details.</p><h3>What’s New in Core ML 4</h3><h3>1. MLTensor: A Simpler, More Efficient API</h3><p>Core ML 4 introduces the <strong>MLTensor</strong> type, a multimensional-array API that mirrors frameworks like NumPy and TensorFlow. This makes it far easier to inspect, manipulate, and pass tensor data into your models without boilerplate conversion code.</p><h3>2. Multifunction &amp; Stateful Models</h3><p>Gone are the days of one-function-per-model. With <strong>multifunction models</strong>, you can bundle image preprocessing, classification, and postprocessing steps into a single .mlmodel—reducing app bloat and improving integration. Plus, <strong>stateful models</strong> let you cache intermediate results (like feature embeddings) across multiple inferences for big speedups in tasks like object tracking or language generation .</p><h3>3. Granular Model Compression &amp; Execution Insights</h3><p>Core ML Tools now supports <strong>weight compression techniques</strong> — pruning, quantization, and distillation — so you can ship large-language or diffusion models on device with minimal footprint. And Xcode’s <strong>Core ML Performance Reports </strong>highlight which operations run on CPU, GPU, or the Neural Engine, giving you a clear path to squeeze out extra FPS or lower memory usage.</p><h3>On-Device Personalization &amp; Training</h3><p>While Core ML has long excelled at inference, Core ML 4 makes <strong>on-device updates</strong> a reality. Using the <strong>updatable model</strong> API, you can gather user-specific data — say, personalization feedback or keyboard corrections — and fine-tune a shipped .mlmodel at runtime. This unlocks hyper-personalized experiences without ever sending raw data to your servers.</p><p>If you prefer a GUI approach, Apple’s <strong>Create ML</strong> app now offers interactive previews and templates for time-series forecasting, object tracking, and custom classification models. Build your model on Mac, then drag-and-drop the resulting Core ML file right into Xcode.</p><h3>Leveraging Apple Silicon &amp; the Neural Engine</h3><p>Core ML is deeply optimized for Apple’s custom silicon. The latest <strong>M4 Neural Engine</strong> delivers up to 38 TOPS for ML tasks, powering everything from live camera segmentation to on-device generative text completion. By default, Core ML will route supported operations to the Neural Engine for peak performance and energy efficiency — no extra code required</p><h3>Real-World Use Cases</h3><ul><li><strong>Image Classification &amp; Object Detection</strong><br>Ship a fine-tuned MobileNetV3 or YOLOv5 model to detect scenes and objects in real time — perfect for retail, fitness, or AR shopping apps.</li><li><strong>Natural Language Processing</strong><br>Integrate transformer-based sentiment analysis or summarization directly in your chat or email app with no server dependencies.</li><li><strong>Generative AI</strong><br>Use compressed diffusion models for on-device image generation or Core ML’s new sequence-to-sequence templates to power text-to-text features — all while guaranteeing user data never leaves the device.</li></ul><h3>Getting Started</h3><ol><li><strong>Install the Core ML Tools CLI</strong>:</li></ol><pre>pip install coremltools</pre><p><strong>2. Convert Your Model</strong>:</p><pre>import coremltools as ct<br>mlmodel = ct.convert(&quot;my_model.onnx&quot;,<br>                     convert_to=&quot;mlprogram&quot;,<br>                     compute_units=ct.ComputeUnit.CPU_AND_NEURAL_ENGINE)<br>mlmodel.save(&quot;MyModel.mlpackage&quot;)</pre><p><strong>3. Inspect with Xcode</strong>:<br>Drag your .mlpackage into Xcode, then open the <strong>Model Debugger</strong> to review performance estimates and layer-by-layer execution locations.</p><p><strong>4. Integrate in Swift</strong>:</p><pre>let config = MLModelConfiguration()<br>config.computeUnits = .all<br>let model = try MyModel(configuration: config)<br>let input = MyModelInput(image: uiImage)<br>let output = try model.prediction(input: input)</pre><p><strong>5. Fine-Tune On Device</strong> (optional):</p><pre>let updateTask = try model.updateTask(<br>  for: trainingData,<br>  configuration: .init(),<br>  completionHandler: { context in<br>    print(&quot;Training finished:&quot;, context.metrics)<br>  })<br>updateTask.resume()</pre><h3>Conclusion</h3><p>Core ML 4 represents a massive leap forward for on-device intelligence — whether you’re building privacy-first health apps, immersive AR experiences, or offline-ready utilities. By taking advantage of <strong>MLTensor</strong>, <strong>multifunction models</strong>, and <strong>on-device personalization</strong>, you can deliver responsive, secure, and bespoke features that delight users.</p><p>Excited to try it out? Check out Apple’s official <a href="https://developer.apple.com/documentation/coreml/">Core ML Documentation</a> and the WWDC24 talk “Deploy machine learning and AI models on-device with Core ML” to dive deeper.</p><p>Let me know what you build next!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b11a4a5777" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Prioritize Building Offline-First iOS Apps Now]]></title>
            <link>https://medium.com/@almehawas/why-i-prioritize-building-offline-first-ios-apps-now-c0f8a7c22e91?source=rss-209e1066ef9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0f8a7c22e91</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Fahad Almehawas]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 08:25:50 GMT</pubDate>
            <atom:updated>2025-04-28T08:25:50.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fIFSbf6Tdakc_D0NjtUBtQ.png" /></figure><p>When I started building iOS apps, I didn’t think much about what would happen if the network was down.<br>I figured, “It’s 2025, people always have internet.” Right?</p><h3>Wrong.</h3><p>After shipping a few apps into the real world, I learned the hard way: <strong>bad network experiences destroy user trust</strong>.<br>And mobile networks are <em>way</em> more fragile than you’d think — elevators, basements, rural areas, crowded concerts — users lose signal <em>all the time</em>.</p><p>Today, every app I build is designed <strong>offline-first</strong> by default.<br>Here’s how — and why — it completely changed the quality of my apps.</p><h3>A Wake-Up Call: Real Users, Real Problems</h3><p>In one of my early apps, users could view and submit reports.<br>Everything was server-driven: loading the list, submitting a new report, updating details — all live network calls.<br>No network = nothing worked.</p><p>The 1-star reviews poured in:</p><blockquote><em>“App freezes when I have no service!”<br>“Lost all my work when I entered a tunnel!”<br>“Extremely slow loading. Useless offline.”</em></blockquote><p>It was a brutal but necessary lesson:<br><strong>Users expect apps to <em>work</em> even when the internet doesn’t.</strong></p><h3>Offline-First: What It Actually Means</h3><p>Building offline-first doesn’t mean you never touch the network.<br>It means:</p><ul><li><strong>Data loads instantly from local storage first.</strong></li><li><strong>Background sync happens quietly and gracefully.</strong></li><li><strong>User actions are queued and retried if needed.</strong></li></ul><p>The user should <em>never</em> feel like they’re waiting on the network.</p><h3>The Core Building Blocks</h3><p>Here’s what I started using to make it happen:</p><h3>1. Local Storage</h3><p>Depending on the data, I choose:</p><ul><li>Core Data (for relational models)</li><li>Realm (for simpler, fast syncing models)</li><li>FileManager (for documents, media files)</li><li>NSCache (for temporary in-memory caching)</li></ul><p>Example: Caching a fetched object locally with Core Data:</p><pre>func cacheUserProfile(_ profile: UserProfile) {<br>    let context = persistentContainer.viewContext<br>    let entity = UserEntity(context: context)<br>    entity.name = profile.name<br>    entity.email = profile.email<br>    try? context.save()<br>}</pre><p>When the app launches, it <strong>loads from Core Data first</strong>, then refreshes quietly in the background if needed.</p><h3>2. Background Sync</h3><p>Swift Concurrency made it way easier to write background refreshes:</p><pre>func refreshUserProfile() async {<br>    do {<br>        let profile = try await api.fetchUserProfile()<br>        cacheUserProfile(profile)<br>    } catch {<br>        print(&quot;Failed to refresh: \(error)&quot;)<br>    }<br>}</pre><p>With a Task, I can fetch new data without blocking the user’s experience.</p><p>Bonus: I use URLSession&#39;s background transfers for large downloads. Even if the app is killed, iOS handles it beautifully.</p><h3>3. Queuing Offline Actions</h3><p>What if a user posts a comment offline?</p><p>Instead of throwing an error, I <strong>queue</strong> it locally:</p><pre>struct PendingAction: Codable {<br>    let id: UUID<br>    let endpoint: URL<br>    let payload: Data<br>}<br><br>var pendingActions: [PendingAction] = []<br><br>func queueAction(_ action: PendingAction) {<br>    pendingActions.append(action)<br>    savePendingActionsToDisk()<br>}</pre><p>Then, whenever the network comes back, I retry them:</p><pre>func syncPendingActions() async {<br>    for action in pendingActions {<br>        do {<br>            try await api.post(action.endpoint, payload: action.payload)<br>            removeAction(action)<br>        } catch {<br>            print(&quot;Will retry later: \(error)&quot;)<br>        }<br>    }<br>}</pre><p>Users can submit stuff <strong>instantly</strong>, even without a signal.<br>And when their network is good again, everything syncs invisibly.</p><h3>Subtle UX Wins</h3><p>Going offline-first doesn’t just solve technical problems — it unlocks <strong>huge UX wins</strong>:</p><ul><li>App launches feel <em>instant</em> because you always show cached data.</li><li>No ugly spinners or timeout alerts.</li><li>Users feel like your app is <em>reliable</em> and <em>trustworthy</em>.</li></ul><p>Even better, it shows respect for users in low-connectivity regions — making your app more <strong>accessible</strong> and <strong>inclusive</strong>globally.</p><h3>It’s a Mindset Shift, Not Just a Feature</h3><p>The biggest change wasn’t technical — it was <strong>mental</strong>.<br>I started assuming:</p><ul><li>The network is <em>unavailable</em>.</li><li>Data is <em>stale</em>.</li><li>Sync will <em>eventually</em> succeed.</li></ul><p>If you start from those assumptions, you build smarter, stronger apps.</p><h3>Final Thoughts</h3><p>Going offline-first made me a better iOS developer.<br>It forced me to think about <em>resilience</em>, <em>performance</em>, and <em>user experience</em> at a deeper level.</p><p>And funny enough, when your app <strong>handles bad conditions well</strong>,<br>it absolutely <strong>shines</strong> when conditions are good.</p><p>Next time you start a new project, ask yourself:<br><strong>“If the network dies, does my app still work?”</strong><br>If the answer is yes — you’re building something great.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0f8a7c22e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Swift Concurrency Changed the Way I Build iOS Apps]]></title>
            <link>https://medium.com/@almehawas/how-swift-concurrency-changed-the-way-i-build-ios-apps-3c4af0fc3cb9?source=rss-209e1066ef9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c4af0fc3cb9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Fahad Almehawas]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 08:06:44 GMT</pubDate>
            <atom:updated>2025-04-28T08:06:44.044Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLPZBKyBhUOQ7kmgxTQMuQ.png" /></figure><h3>Introduction</h3><p>When Apple introduced <strong>Swift Concurrency</strong> at WWDC 2021, it fundamentally shifted how I think about building apps. Before that, I heavily relied on <strong>Grand Central Dispatch (GCD)</strong> and <strong>Operation Queues</strong>, manually managing queues and synchronization. It worked, but it could get <strong>messy</strong>, <strong>hard to debug</strong>, and <strong>error-prone</strong>.</p><p>Here’s how Swift Concurrency changed my development style:</p><h3>1. Code Became Linear and Readable</h3><p>Before:</p><pre>DispatchQueue.global().async {<br>    let data = fetchData()<br>    DispatchQueue.main.async {<br>        updateUI(with: data)<br>    }<br>}</pre><p>After:</p><pre>func loadData() async {<br>    let data = await fetchData()<br>    updateUI(with: data)<br>}</pre><p>With async/await, the code reads <strong>top-down</strong>, like it’s synchronous, but it&#39;s actually asynchronous under the hood. It <strong>reduced mental overhead</strong> and <strong>bugs</strong> caused by forgetting which queue I was on.</p><h3>2. Structured Concurrency = Safer Lifecycles</h3><p>Before Swift Concurrency, tasks launched with GCD could easily <strong>outlive</strong> their scope or <strong>leak</strong>. With Swift’s <strong>structured concurrency</strong>, tasks are <strong>bound to the lifetime</strong> of their parent task:</p><pre>func viewDidLoad() {<br>    Task {<br>        await fetchData()<br>    }<br>}</pre><p>If the view controller goes away, so does the task, preventing memory leaks and zombie work.</p><h3>3. Actors Made State Management Way Safer</h3><p>Managing shared mutable state across threads was a nightmare. Now, I use <strong>actors</strong> to isolate and protect state automatically:</p><pre>actor Counter {<br>    private var value = 0<br><br>    func increment() {<br>        value += 1<br>    }<br><br>    func current() -&gt; Int {<br>        value<br>    }<br>}</pre><p>No more worrying about race conditions or manually locking with semaphores or queues.</p><h3>4. Task Groups Supercharged Parallelism</h3><p>Instead of manually dispatching multiple async operations and manually tracking completion, I now use <strong>Task Groups</strong>:</p><pre>func fetchAllData() async {<br>    await withTaskGroup(of: Data.self) { group in<br>        for url in urls {<br>            group.addTask {<br>                await fetchData(from: url)<br>            }<br>        }<br><br>        for await data in group {<br>            process(data)<br>        }<br>    }<br>}</pre><p>Massive parallelism — but <strong>organized</strong>, <strong>safe</strong>, and <strong>cancelable</strong>.</p><h3>5. AsyncSequence Simplified Asynchronous Streams</h3><p>Listening to a stream of data (e.g., notifications, network events) used to require callbacks or Combine. Now, AsyncSequence lets me write:</p><pre>for await message in messageStream {<br>    handle(message)<br>}</pre><p>Way cleaner.</p><h3>In Short</h3><ul><li>Swift Concurrency made <strong>asynchronous programming feel synchronous</strong>.</li><li>It <strong>reduced boilerplate</strong>, <strong>increased safety</strong>, and <strong>made bugs rarer</strong>.</li><li>It encouraged a <strong>more functional</strong>, <strong>modular</strong> design style.</li><li>Debugging async code became easier with <strong>Xcode’s concurrency debugging tools</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c4af0fc3cb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Singly Linked Lists in Swift]]></title>
            <link>https://medium.com/@almehawas/understanding-singly-linked-lists-in-swift-51aaf300e46f?source=rss-209e1066ef9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51aaf300e46f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[linked-list-program]]></category>
            <dc:creator><![CDATA[Fahad Almehawas]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 13:22:47 GMT</pubDate>
            <atom:updated>2024-11-18T13:22:47.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avI1MeVuJhmd_3DhkNriRA.jpeg" /></figure><p><strong>A linked list is one of the many data structures used in computer science to store and manage data. There are several types of linked lists, including:</strong></p><ol><li>Singly Linked List</li><li>Doubly Linked List</li><li>Singly Circular Linked List</li><li>Doubly Circular Linked List</li><li>Multiply Linked List</li><li>Skip List</li><li>Unrolled Linked List</li><li>8. Self-Organizing List</li><li>XOR Linked List</li></ol><p>In this article, we’ll focus specifically on <strong>singly linked lists</strong>, one of the simplest and most commonly used types.</p><blockquote><strong>Simplified Definition:</strong></blockquote><blockquote>Think of a singly linked list like a chain made up of boxes. Each box holds two things: some information (like a number or a word) and a link to the next box in the chain. The boxes are connected one after another, and you can follow the links to move from one box to the next until you reach the end.</blockquote><blockquote><strong>Detailed Definition:</strong></blockquote><p>A <strong>singly linked list</strong> is a data structure where each item (called a node) contains two parts: the data and a pointer (or link) to the next node in the sequence. Unlike arrays, where elements are stored in a contiguous block of memory, a singly linked list stores each item separately, linking them one by one. This structure makes it easy to add or remove items, especially at the beginning, without needing continuous memory space. However, accessing elements requires traversing the list from the beginning since there is no direct indexing.</p><blockquote><strong><em>Practical Use Cases in Mobile and Web Development</em></strong></blockquote><p>Singly linked lists are particularly useful in scenarios where dynamic data management, memory optimization, and efficient insertion/deletion are needed. Here are some common use cases:</p><p><strong>1. Back/Forward Navigation in Browsers</strong></p><ul><li><strong>Use Case</strong>: A singly linked list can track browser navigation history, allowing easy traversal between previously visited pages.</li><li><strong>Why Singly Linked List?</strong>: It enables efficient forward navigation without needing to manage a large block of memory.</li></ul><p><strong>2. Managing Dynamic UI Components (e.g., Menus or Feeds)</strong></p><ul><li><strong>Use Case</strong>: Singly linked lists can manage dynamic content, such as items in a chat or social media feed, where items are frequently added or removed.</li><li><strong>Why Singly Linked List?</strong>: Items can be inserted or removed efficiently without rearranging other elements.</li></ul><p><strong>3. Undo/Redo Functionality</strong></p><ul><li><strong>Use Case</strong>: In text editors or drawing apps, each action can be represented as a node in a singly linked list to enable undo/redo functionality.</li><li><strong>Why Singly Linked List?</strong>: It allows efficient traversal between user actions.</li></ul><p><strong>4. Task Scheduling</strong></p><ul><li><strong>Use Case</strong>: Singly linked lists can manage a queue of tasks (e.g., background jobs or notifications) that need to be processed in sequence.</li><li><strong>Why Singly Linked List?</strong>: Tasks can be dynamically added or removed as needed.</li></ul><p><strong>5. Memory Allocation</strong></p><ul><li><strong>Use Case</strong>: A singly linked list can keep track of free memory blocks in applications that need to manage memory efficiently.</li><li><strong>Why Singly Linked List?</strong>: Nodes representing memory can be efficiently inserted or removed as needed.</li></ul><p><strong>6. Real-time Data Streams</strong></p><ul><li><strong>Use Case</strong>: Managing real-time data streams (e.g., live chat or stock tickers) where new data frequently arrives.</li><li><strong>Why Singly Linked List?</strong>: New data can be added to the beginning or end without resizing.</li></ul><p><strong>7. Implementing Hash Tables (with Chaining)</strong></p><ul><li><strong>Use Case</strong>: Singly linked lists can handle hash collisions in hash tables using chaining.</li><li><strong>Why Singly Linked List?</strong>: It allows efficient storage and retrieval of collided elements.</li></ul><p><strong>8. Media Playlists</strong></p><ul><li><strong>Use Case</strong>: Singly linked lists can manage dynamic media playlists in music or video streaming apps.</li><li><strong>Why Singly Linked List?</strong>: Songs or videos can be easily added or removed without shifting elements.</li></ul><p><strong>9. Breadcrumb Navigation</strong></p><ul><li><strong>Use Case</strong>: A singly linked list can represent breadcrumb navigation in web apps.</li><li><strong>Why Singly Linked List?</strong>: It allows for efficient traversal and updates as the user navigates through pages.</li></ul><p><strong>10. Sparse Matrix Representation</strong></p><ul><li><strong>Use Case</strong>: In data visualization or apps with large datasets, singly linked lists can represent sparse matrices, reducing memory usage.</li></ul><p>• <strong>Why Singly Linked List?</strong>: Only non-empty elements are stored, saving memory.</p><blockquote><strong>Advantages and Disadvantages of Singly Linked Lists</strong></blockquote><h4><em>Advantages:</em></h4><ol><li><strong>Dynamic Size</strong>:</li></ol><ul><li>Singly linked lists can grow or shrink as needed, making them ideal when the number of elements is unknown in advance.</li></ul><p><strong>2. Efficient Insertions/Deletions</strong>:</p><ul><li>Inserting or deleting nodes at the beginning of the list is efficient (O(1)) and requires updating only a few pointers.</li></ul><p><strong>3. Memory Efficiency</strong>:</p><ul><li>Linked lists don’t require a continuous block of memory, which is useful when memory is fragmented.</li></ul><p><strong>4. No Pre-allocation Needed</strong>:</p><ul><li>Nodes are created as needed, avoiding wasted space.</li></ul><p><strong>5. Flexibility for Implementing Stacks and Queues</strong>:</p><p>• Singly linked lists can be easily used to implement stacks or queues due to their flexibility in adding/removing items.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Disadvantages:</strong></p><ol><li><strong>Sequential Access</strong>:</li></ol><ul><li>Accessing elements requires starting from the head and traversing the list, which has a time complexity of O(n), unlike arrays that allow direct access.</li></ul><p><strong>2. Extra Memory for Pointers</strong>:</p><ul><li>Each node requires additional memory for the pointer to the next node, which can add up.</li></ul><p><strong>3. No Backward Traversal</strong>:</p><ul><li>Singly linked lists allow only forward traversal. If reverse traversal is needed, doubly linked lists are more suitable.</li></ul><p><strong>4. Slower Search Operations</strong>:</p><ul><li>Searching for elements in a singly linked list requires O(n) time, as each node must be traversed.</li></ul><p><strong>5. Pointer Management Complexity</strong>:</p><p>• Managing pointers can introduce complexity and potential errors, such as memory leaks or losing track of nodes.</p><blockquote><strong>Singly Linked List Implementation in Swift</strong></blockquote><p>Here’s a basic implementation of a singly linked list in Swift, including common operations like insertion, deletion, and traversal:</p><pre>// Node class representing each element of the linked list<br>class Node&lt;T&gt; {<br>    var value: T<br>    var next: Node?<br><br>    init(value: T) {<br>        self.value = value<br>        self.next = nil<br>    }<br>}<br><br>// Singly Linked List class<br>class SinglyLinkedList&lt;T&gt; {<br>    var head: Node&lt;T&gt;?<br><br>    // Check if the list is empty<br>    func isEmpty() -&gt; Bool {<br>        return head == nil<br>    }<br><br>    // Insert a node at the beginning of the list<br>    func insertAtBeginning(value: T) {<br>        let newNode = Node(value: value)<br>        newNode.next = head<br>        head = newNode<br>    }<br><br>    // Insert a node at the end of the list<br>    func insertAtEnd(value: T) {<br>        let newNode = Node(value: value)<br>        if isEmpty() {<br>            head = newNode<br>        } else {<br>            var current = head<br>            while current?.next != nil {<br>                current = current?.next<br>            }<br>            current?.next = newNode<br>        }<br>    }<br><br>    // Delete the first node with the given value<br>    func delete(value: T) {<br>        if isEmpty() {<br>            print(&quot;List is empty. Cannot delete.&quot;)<br>            return<br>        }<br><br>        if head?.value == value {<br>            head = head?.next<br>            return<br>        }<br><br>        var current = head<br>        var previous: Node&lt;T&gt;?<br><br>        while current != nil &amp;&amp; current?.value != value {<br>            previous = current<br>            current = current?.next<br>        }<br><br>        if current == nil {<br>            print(&quot;Value not found in the list.&quot;)<br>        } else {<br>            previous?.next = current?.next<br>        }<br>    }<br><br>    // Display the entire list<br>    func display() {<br>        if isEmpty() {<br>            print(&quot;List is empty.&quot;)<br>            return<br>        }<br><br>        var current = head<br>        while current != nil {<br>            print(current!.value, terminator: &quot; -&gt; &quot;)<br>            current = current?.next<br>        }<br>        print(&quot;nil&quot;)<br>    }<br><br>    // Search for a value in the list<br>    func search(value: T) -&gt; Bool {<br>        var current = head<br>        while current != nil {<br>            if current?.value == value {<br>                return true<br>            }<br>            current = current?.next<br>        }<br>        return false<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51aaf300e46f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>