<?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 Omar Saibaa on Medium]]></title>
        <description><![CDATA[Stories by Omar Saibaa on Medium]]></description>
        <link>https://medium.com/@omar.saibaa?source=rss-aad284ffbae6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YjDOlNz_SlMVnUqvzAWu0g.jpeg</url>
            <title>Stories by Omar Saibaa on Medium</title>
            <link>https://medium.com/@omar.saibaa?source=rss-aad284ffbae6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:47:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omar.saibaa/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[Prefix Sum Array]]></title>
            <link>https://blog.stackademic.com/prefix-sum-array-25959cb6fcf9?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/25959cb6fcf9</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[prefix-sum]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Mon, 13 May 2024 10:17:29 GMT</pubDate>
            <atom:updated>2024-05-13T10:17:29.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfOIcXeBuJ6YKqFlKl-SHQ.png" /></figure><p>A prefix sum array, also known as a cumulative sum array, is a data structure that efficiently calculates the sum of subarrays within a larger array. It’s a derived array where each element represents the cumulative sum of elements in the original array up to that index.</p><h4><strong>How It Works</strong></h4><ul><li>Given an array arr[] of size N.</li><li>Create a new array prefixSum[] of the same size.</li><li>Initialize prefixSum[0] to arr[0]. This is because the sum up to the first element is just the element itself.</li><li>Iterate through arr[] from index 1 to N-1.</li><li>For each index i in prefixSum[], calculate prefixSum[i] as the sum of prefixSum[i-1] (previous cumulative sum) and arr[i] (current element).</li></ul><p>This builds prefixSum[] where prefixSum[i] holds the sum of arr[0] + arr[1] + ... + arr[i].</p><h4><strong>Benefits of Prefix Sum Arrays</strong></h4><ul><li><strong>Efficient Subarray Sum Queries:</strong> Finding the sum of elements within a range [start, end] in the original array can be done in constant time (O(1)) using prefix sum. You simply calculate prefixSum[end] - prefixSum[start-1] (assuming prefixSum[0] is initialized to 0).</li><li><strong>Faster Updates:</strong> If you need to update elements in the original array and maintain the prefix sum array, it can be done efficiently. You only need to update the corresponding element and the elements following it in the prefix sum array to reflect the change.</li></ul><h4><strong>When to Use Prefix Sum Arrays</strong></h4><ul><li>Prefix sum arrays are ideal when you need to perform frequent subarray sum queries on the same array.</li><li>They are particularly useful in problems involving finding running totals, averages, or applying segment tree operations.</li></ul><h4><strong>When Not to Use Prefix Sum Arrays</strong></h4><ul><li>If you only need the sum of the entire array once, a simple loop through the original array is sufficient.</li><li>If space complexity is a major concern and subarray sum queries are infrequent, using the original array might be preferable.</li></ul><h4><strong>Steps to Think About When Using Prefix Sum Arrays</strong></h4><ol><li>Identify the problem: Are you dealing with frequent subarray sum queries or calculations involving cumulative sums?</li><li>Analyze time complexity: Will using a prefix sum array significantly improve the efficiency of your code compared to iterating over the original array?</li><li>Consider space complexity: Do you have enough memory to store the prefix sum array in addition to the original array?</li></ol><h4><strong>Real-Life Example: Calculating Average Rainfall</strong></h4><p>Imagine you have an array rainfall representing daily rainfall measurements. You want to find the average rainfall for a specific period (days start to end).</p><ol><li>Create a prefix sum array prefixSum for rainfall.</li><li>The average rainfall for days start to end can be calculated as:</li></ol><p>(prefixSum[end] - prefixSum[start-1]) / (end - start + 1)</p><p>Let’s implement prefix sum and calculate average rainfall in Swift:</p><pre>func prefixSum(_ arr: [Int]) -&gt; [Int] {<br>  var prefixSums = [Int](repeating: 0, count: arr.count)<br>  prefixSums[0] = arr[0]<br>  for i in 1..&lt;arr.count {<br>    prefixSums[i] = prefixSums[i - 1] + arr[i]<br>  }<br>  return prefixSums<br>}<br><br>func averageRainfall(_ rainfall: [Int], _ start: Int, _ end: Int) -&gt; Double {<br>  let prefixSums = prefixSum(rainfall)<br>  let totalRain = prefixSums[end] - (start &gt; 0 ? prefixSums[start - 1] : 0)<br>  return Double(totalRain) / Double(end - start + 1)<br>}<br><br>// Example usage<br>let rainfall = [2, 5, 1, 3, 4]<br>let averageRain = averageRainfall(rainfall, 2, 4)  // Average rainfall from day 3 to day 5<br>print(averageRain)  // Output: 3.33</pre><p>In this example, the prefixSum function calculates the prefix sum array, and averageRainfall efficiently finds the average rain for a specific period using the prefix sum approach.</p><h3>Now Let’s Move to solve LeetCode Problem using Prefix Sum Array:</h3><p>the problem is <a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/description/">https://leetcode.com/problems/subarray-sums-divisible-by-k/description/</a></p><p>so read it , understand it , try to solve it , then read next solution:</p><pre>func subarraysDivByK(_ nums: [Int], _ k: Int) -&gt; Int {<br>        var remainderCount: [Int: Int] = [0: 1]<br>        var result = 0<br><br>        var currentSum = 0<br>        for num in nums {<br>            currentSum += num<br>            let remainder = (currentSum % k + k) % k<br><br>            if let count = remainderCount[remainder] {<br>                result += count<br>            }<br>            remainderCount[remainder, default: 0] += 1<br>        }<br><br>        return result<br>}</pre><h4><strong>Explanation:</strong></h4><ul><li>The key idea is that if two subarrays have the same remainder when their sums are divided by k, the difference of their sums will also be divisible by k.</li><li>By keeping track of the remainders of prefix sums, we can efficiently count subarrays with sums divisible by k.</li><li>The remainderCount dictionary stores the frequency of each remainder encountered.</li><li>When a new remainder is encountered, it signifies a new subarray starting with that remainder.</li><li>If the same remainder is encountered again, it means a subarray ending with that remainder has been found, and we increment its count.</li><li>Since the empty subarray with a sum of 0 is considered divisible by k, we initialize remainderCount[0] to 1.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25959cb6fcf9" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/prefix-sum-array-25959cb6fcf9">Prefix Sum Array</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Pointers Pattern]]></title>
            <link>https://blog.stackademic.com/two-pointers-pattern-7c80ded2ee73?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c80ded2ee73</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Mon, 13 May 2024 04:17:31 GMT</pubDate>
            <atom:updated>2024-05-13T04:17:31.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*RPAsaMsY-qMfdjta" /></figure><h4><strong>What is the Two-Pointer </strong>Pattern<strong>?</strong></h4><p>The two-pointer is a versatile algorithmic Pattern used to traverse and manipulate data structures, particularly arrays and strings, in an efficient manner. It involves employing two pointers that move through the data structure according to specific conditions.</p><h4><strong>Benefits:</strong></h4><ul><li><strong>Efficiency:</strong> The two-pointer approach often reduces time complexity by cleverly navigating the data structure without unnecessary iterations. This is especially beneficial for sorted arrays.</li><li><strong>Minimal Space Complexity:</strong> It typically uses constant extra space (O(1)), making it memory-efficient.</li><li><strong>Elegance and Readability:</strong> The two-pointer can lead to concise and clear code compared to brute-force approaches.</li></ul><h4><strong>When to Use Two Pointers:</strong></h4><ul><li><strong>Problems involving sorted arrays:</strong> The two-pointer shines when working with sorted arrays. You can leverage the sorted nature to efficiently solve problems like finding pairs with a given sum, removing duplicates, or checking if a string is a palindrome.</li><li><strong>Sliding window problems:</strong> This pattern is well-suited for scenarios where you need to maintain a window of elements that meet a certain criterion. Examples include finding the maximum sum subarray within a specific size or finding the longest substring with k distinct characters.</li></ul><h4><strong>When Not to Use Two Pointers:</strong></h4><ul><li><strong>Unsorted arrays:</strong> If the array is not sorted, the two-pointer approach might not be the most efficient or even applicable. In such cases, consider using techniques like hashing or sorting the array first.</li><li><strong>Linked lists:</strong> While the two-pointer can be adapted for linked lists in some cases, it’s generally less common due to the lack of random access and the need for additional logic to handle node pointers.</li></ul><h4><strong>Template for Two Pointers in Swift:</strong></h4><ol><li><strong>Initialize pointers:</strong></li></ol><ul><li>Create two integer variables, typically named left and right, to represent the pointers.</li><li>In most cases, initialize left to 0 (the beginning of the data structure) and right to the last index (or one less than the length).</li></ul><p><strong>2. Loop with condition:</strong></p><ul><li>Employ a while loop that continues as long as both pointers haven&#39;t met or exceeded the valid range of the data structure.</li></ul><p><strong>3. Check and update:</strong></p><ul><li>Within the loop, implement a condition that compares the elements pointed to by left and right. Based on the problem you&#39;re solving, this condition might involve:</li><li>Checking for a specific relationship between the elements (e.g., their sum, equality, or relative order).</li><li>Using the values to modify the data structure (e.g., swapping elements or removing duplicates).</li><li>Update one or both pointers (left++, right--, or a combination) based on the condition and the desired traversal direction.</li></ul><p><strong>4. Return or modify:</strong></p><ul><li>After the loop terminates, you might return a result (e.g., a boolean value indicating if a condition is met or the indices of elements that satisfy the problem). Alternatively, you might directly modify the data structure within the loop.</li></ul><h4><strong>Now Let’s Implement last template on real problem:</strong></h4><p>Imagine you’re organizing a group of people for a photo. You want to arrange them in alternating heights (tall-short-tall-short…). You have their heights stored in a sorted array heights.</p><p><strong>Solution using Two Pointers:</strong></p><pre>func arrangeByHeight(_ heights: [Int]) -&gt; [Int] {<br>    if heights.isEmpty { return [] }<br><br>    var result = heights // Copy the array to avoid modifying the original<br>    var i = 0 // Short pointer (starts at the beginning)<br>    var j = result.count - 1 // Tall pointer (starts at the end)<br><br>    for index in 0..&lt;result.count {<br>        if index % 2 == 0 { // Even index (place a tall person)<br>            result[index] = heights[j]<br>            j -= 1<br>        } else { // Odd index (place a short person)<br>            result[index] = heights[i]<br>            i += 1<br>        }<br>    }<br><br>    return result<br>}<br><br>// Example usage<br>let heights = [160, 150, 170, 180, 165]<br>let arrangedHeights = arrangeByHeight(heights)<br>print(arrangedHeights) // Output: [180, 150, 170, 160, 165]</pre><h4><strong>Explanation:</strong></h4><ol><li><strong>Initialize pointers:</strong></li></ol><ul><li>i starts at 0 (short pointer) to place the shortest person first.</li><li>j starts at the last index (tall pointer) to place the tallest person first.</li></ul><p><strong>2. Loop with condition:</strong></p><ul><li>The for loop iterates through the entire result array.</li></ul><p><strong>3. Check and update:</strong></p><ul><li>The condition index % 2 == 0 checks if the current index is even (place a tall person).</li><li>If even, copy the element from heights[j] (using the tall pointer) to result[index] and decrement j.</li><li>Otherwise (odd index), copy the element from heights[i] (using the short pointer) to result[index] and increment i.</li></ul><p><strong>4. Return or modify:</strong></p><ul><li>The function returns the modified result array with people arranged by alternating heights.</li></ul><h3>Now Let’s Move to solve LeetCode Problem using Two Pointer:</h3><p>the problem is <a href="https://leetcode.com/problems/valid-palindrome/">125. Valid Palindrome</a>:</p><p>so read it , understand it , try to solve it , then read next solution:</p><pre>class Solution {<br>    func isPalindrome(_ s: String) -&gt; Bool {<br>    var lowercasedString = s.lowercased() <br>    var left = lowercasedString.startIndex<br>    var right = lowercasedString.index(before: lowercasedString.endIndex)<br><br>    while left &lt; right {<br>      let leftChar = lowercasedString[left]<br>      let rightChar = lowercasedString[right]<br><br>      if !isAlphanumeric(leftChar) {<br>          left = lowercasedString.index(after: left)<br>      } else if !isAlphanumeric(rightChar) {<br>          right = lowercasedString.index(before: right)<br>      } else if leftChar != rightChar {<br>          return false<br>      } else {<br>          left = lowercasedString.index(after: left)<br>          right = lowercasedString.index(before: right)<br>      }<br>    }<br>  return true<br>}<br><br>    func isAlphanumeric(_ char: Character) -&gt; Bool {<br>        return char.isLetter || char.isNumber<br>    }<br><br><br>}</pre><h4>Explanation:</h4><ol><li><strong>Initialize Pointers:</strong></li></ol><ul><li>left is initialized to the startIndex of the lowercasedString.</li><li>right is initialized to the index before the endIndex of the lowercasedString.</li></ul><p><strong>2. Loop with Condition:</strong></p><ul><li>The while loop continues as long as left is less than right (i.e., the pointers haven&#39;t met or crossed each other).</li></ul><p><strong>3. Check and Update:</strong></p><ul><li>Inside the loop:</li><li>leftChar and rightChar store the characters at the current positions of left and right pointers.</li><li>The isAlphanumeric function checks if the characters are alphanumeric.</li><li>If either leftChar or rightChar is not alphanumeric, the corresponding pointer (left or right) is moved to skip non-alphanumeric characters.</li><li>If both characters are alphanumeric and not equal, it means the string is not a palindrome, so the function returns false.</li><li>If both characters are alphanumeric and equal, both pointers move one step closer to the center (left forward, right backward).</li></ul><p><strong>4. Return or Modify:</strong></p><ul><li>After the loop finishes (left &gt;= right), if no mismatches were found, the string is a palindrome, and the function returns true.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c80ded2ee73" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/two-pointers-pattern-7c80ded2ee73">Two Pointers Pattern</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brute Force Approach]]></title>
            <link>https://blog.stackademic.com/brute-force-approach-58ed87b7a0b7?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/58ed87b7a0b7</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[brute-force]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Mon, 13 May 2024 00:25:26 GMT</pubDate>
            <atom:updated>2024-05-13T00:25:26.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*99vSyJksy0MfnNtY.jpg" /></figure><p>A brute force approach is a straightforward problem-solving strategy that entails systematically checking every single possible solution until the correct one is found. It’s like trying every key on a keyring until you find the one that unlocks the door.</p><h4><strong>How it Works</strong></h4><ol><li><strong>Define the Problem:</strong> The first step is to clearly understand the problem you’re trying to solve.</li><li><strong>Identify All Possibilities:</strong> Next, you need to figure out all the potential solutions. This could involve listing out every option, creating an algorithm to generate them, or using a trial-and-errror method.</li><li><strong>Systematically Check:</strong> With all the possibilities identified, you start testing each one against the problem constraints. This might involve evaluating each option or running a simulation to see if it yields the desired outcome.</li><li><strong>Stop at the Solution:</strong> The process continues until you find a solution that meets the problem’s criteria. Once you find it, you can halt the search.</li></ol><h4><strong>Benefits of Brute Force</strong></h4><ul><li><strong>Simplicity:</strong> Brute force is a very easy-to-understand and implement approach. It doesn’t require any complex algorithms or advanced knowledge.</li><li><strong>Guaranteed Solution:</strong> As long as you consider every possibility, brute force guarantees that you’ll eventually find a solution, if one exists.</li></ul><h4>Disadvantages<strong> of Brute Force</strong></h4><ul><li><strong>Inefficiency:</strong> The biggest drawback of brute force is its inefficiency, especially for problems with a large number of possibilities. Checking every single option can be extremely time-consuming and resource-intensive.</li><li><strong>Not Scalable:</strong> Brute force approaches become impractical for problems with vast solution spaces. The time and resources required to explore every possibility can become astronomical.</li></ul><h4><strong>When to Use Brute Force</strong></h4><ul><li><strong>Small Problem Sizes:</strong> If the problem has a manageable number of solutions, brute force can be a viable option.</li><li><strong>Limited Knowledge:</strong> When you don’t have any specific knowledge about the problem or a more efficient algorithm isn’t available, brute force might be your best bet.</li><li><strong>Simplicity is Key:</strong> In situations where a quick and simple solution is more important than efficiency, brute force can be a good choice.</li></ul><h4><strong>Real-Life Example: Cracking a Pin</strong></h4><p>Imagine you need to crack a 4-digit pin. Using brute force, you would:</p><ol><li>Define the Problem: Crack the 4-digit pin.</li><li>Identify Possibilities: All possible 4-digit combinations (0000 to 9999).</li><li>Systematically Check: Try each of the 10,000 combinations (using a pin pad or a program) until you find the correct one.</li></ol><h3>Now Let’s Move to solve LeetCode Problem using Brute Force:</h3><p>the problem is <a href="https://leetcode.com/problems/two-sum/">https://leetcode.com/problems/two-sum/</a></p><p>so read it , understand it , try to solve it , then read next solution.</p><p>The two sum problem asks you to find two numbers in an array that add up to a specific target value. Here’s the solution:</p><pre>func twoSum(_ nums: [Int], _ target: Int) -&gt; [Int] {<br>  for (i, num1) in nums.enumerated() {<br>    for (j, num2) in nums.enumerated() where i != j { // Avoid duplicates<br>      if num1 + num2 == target {<br>        return [i, j]<br>      }<br>    }<br>  }<br>  return [] // No solution found<br>}</pre><h4><strong>Explanation:</strong></h4><ol><li>We use two nested loops to iterate through the nums array.</li></ol><ul><li>The outer loop (i) iterates through the entire array.</li><li>The inner loop (j) starts from the element after the current i (using where i != j) to avoid checking the same element twice.</li></ul><p>2. Inside the loops, we extract the current two elements num1 and num2.</p><p>3. We check if the sum of num1 and num2 equals the target value.</p><p>4. If a match is found, we return an array containing the indices (i and j) of the two numbers.</p><p>5. If no match is found after iterating through all combinations, the function returns an empty array ([]).</p><p><strong>Time Complexity:</strong> O(n²) due to the nested loops. This can be slow for large arrays.</p><p><strong>In conclusion,</strong> brute force is a basic but powerful problem-solving technique. It’s a good choice for small problems, situations with limited knowledge, or when a simple solution is preferred. However, for larger problems or when efficiency is important, it’s essential to explore more complex algorithms.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58ed87b7a0b7" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/brute-force-approach-58ed87b7a0b7">Brute Force Approach</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variadic Function in Swift]]></title>
            <link>https://blog.stackademic.com/variadic-function-in-swift-bdc16933c39b?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc16933c39b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 04:17:35 GMT</pubDate>
            <atom:updated>2024-04-30T04:17:35.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*JM3O47QiHj1-3w1-.jpg" /></figure><p>Variadic functions in Swift are functions that can accept a variable number of arguments of the same type. This allows for more flexible and concise code when you don’t know exactly how many arguments a function might need.</p><h4><strong>Syntax:</strong></h4><p>A variadic parameter is declared by adding three dots (…) after the type of the parameter. For example:</p><pre>func printNames(firstName: String, lastName: String, ...otherNames: String) {<br>  print(&quot;First Name: \(firstName)&quot;)<br>  print(&quot;Last Name: \(lastName)&quot;)<br>  for name in otherNames {<br>    print(&quot;Other Name: \(name)&quot;)<br>  }<br>}</pre><h4><strong>How it Works:</strong></h4><ul><li>Inside the function, the variadic arguments are collected into an array of the specified type.</li><li>You can then iterate through the array to access each argument.</li></ul><h4><strong>Real-world Examples:</strong></h4><p><strong>a) Printing Multiple Names:</strong></p><p>The example function printNames demonstrates how to accept a variable number of names. You can call it with two arguments (first and last name) or with additional names:</p><pre>printNames(firstName: &quot;John&quot;, lastName: &quot;Doe&quot;)   // Prints first and last name<br>printNames(firstName: &quot;Jane&quot;, lastName: &quot;Smith&quot;, otherNames: &quot;Alex&quot;, &quot;Michael&quot;)  // Prints all names</pre><p><strong>b) Calculating Average:</strong></p><p>You can create a function to calculate the average of any number of numbers:</p><pre>func calculateAverage(_ numbers: Double...) -&gt; Double {<br>  var sum = 0.0<br>  for number in numbers {<br>    sum += number<br>  }<br>  return sum / Double(numbers.count)<br>}<br><br>let average1 = calculateAverage(10.0, 20.0)  // Average of 2 numbers<br>let average2 = calculateAverage(5.0, 8.0, 12.0)  // Average of 3 numbers<br>print(&quot;Average 1: \(average1), Average 2: \(average2)&quot;)</pre><h4><strong>Benefits:</strong></h4><ul><li><strong>Flexibility:</strong> Variadic functions handle an unknown number of arguments, making your code adaptable.</li><li><strong>Conciseness:</strong> You can avoid writing multiple functions for different numbers of arguments.</li></ul><h3><strong>Important Note:</strong></h3><p><strong>Consider using default parameters or overloads if there are specific cases with a fixed number of arguments:<br></strong>Imagine you have a function to format a greeting message. You want it to be flexible for different scenarios:</p><ol><li>Greet someone by name (default case)</li><li>Greet someone with a title and name (optional)</li></ol><p>Option 1: Single Variadic Function (Less Readable):</p><p>Swift</p><pre>func greet(name: String, otherWords: String...) {<br>  var message = &quot;Hello, \(name)&quot;<br>  if !otherWords.isEmpty {<br>    message += &quot; &quot; + otherWords.joined(separator: &quot; &quot;)<br>  }<br>  print(message)<br>}<br><br>greet(name: &quot;Alice&quot;) // &quot;Hello, Alice&quot;<br>greet(name: &quot;Bob&quot;, otherWords: &quot;Sir&quot;, &quot;The Magnificent&quot;) // &quot;Hello, Bob Sir The Magnificent&quot;</pre><p>While this works, it can be less readable because you need to check for empty arguments and join them manually.</p><p>Option 2: Default Parameters and Overloads (More Readable):</p><pre>func greet(name: String) {<br>  print(&quot;Hello, \(name)&quot;)<br>}<br><br>func greet(title: String, name: String) {<br>  print(&quot;Hello, \(title) \(name)&quot;)<br>}<br><br>greet(name: &quot;Charlie&quot;) // &quot;Hello, Charlie&quot;<br>greet(title: &quot;Dr.&quot;, name: &quot;Evelyn&quot;) // &quot;Hello, Dr. Evelyn&quot;</pre><p>This approach is clearer:</p><ul><li>One function with a default parameter for a single name.</li><li>Another function overloaded for greetings with a title.</li></ul><p><strong>Benefits:</strong></p><ul><li>Improved readability with clear function signatures.</li><li>Reduced need for conditional checks within the function.</li><li>Potential for type safety with specific parameter types.</li></ul><p><strong>Choosing the Right Approach:</strong></p><ul><li>If the number of arguments can vary significantly, a variadic function might still be suitable.</li><li>But, for situations with specific common cases (like adding a title), default parameters and overloads offer better code clarity and maintainability.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc16933c39b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/variadic-function-in-swift-bdc16933c39b">Variadic Function in Swift</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[== vs === in Swift]]></title>
            <link>https://blog.stackademic.com/vs-in-swift-879c3db8d016?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/879c3db8d016</guid>
            <category><![CDATA[operators]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 16:46:27 GMT</pubDate>
            <atom:updated>2024-04-29T00:46:25.398Z</atom:updated>
            <content:encoded><![CDATA[<p>In Swift, == and === are two comparison operators, but they check for different things:</p><p><strong>1. == (Equal To):</strong></p><ul><li>Checks for <strong>value equality</strong>.</li><li>Used for comparing primitives (like integers, doubles, booleans, and strings) and objects that conform to the Equatable protocol.</li><li>The Equatable protocol defines how to compare two objects for value equality.</li></ul><p><strong>Real-world Example:</strong></p><pre>let number1 = 10<br>let number2 = 10<br><br>if number1 == number2 {<br>  print(&quot;Numbers are equal&quot;)<br>} // Prints &quot;Numbers are equal&quot;<br><br>let name1 = &quot;Alice&quot;<br>let name2 = &quot;Alice&quot;<br><br>if name1 == name2 {<br>  print(&quot;Names are equal&quot;)<br>} // Prints &quot;Names are equal&quot;<br><br>// Custom struct conforming to Equatable<br>struct Point {<br>  let x: Int<br>  let y: Int<br>}<br><br>extension Point: Equatable {<br>  static func == (lhs: Point, rhs: Point) -&gt; Bool {<br>    return lhs.x == rhs.x &amp;&amp; lhs.y == rhs.y<br>  }<br>}<br><br>let point1 = Point(x: 1, y: 2)<br>let point2 = Point(x: 1, y: 2)<br><br>if point1 == point2 {<br>  print(&quot;Points are equal&quot;)<br>} // Prints &quot;Points are equal&quot;</pre><p><strong>2. === (Identical To):</strong></p><ul><li>Checks for <strong>object identity</strong>.</li><li>Determines if two variables refer to the same instance of an object in memory.</li></ul><p><strong>Real-world Example:</strong></p><pre>let number3 = 10<br>let number4 = 10<br><br>if number3 === number4 {<br>  print(&quot;Numbers are identical&quot;)<br>} // Won&#39;t print, numbers are separate instances<br><br>let string1 = &quot;Hello&quot;<br>let string2 = &quot;Hello&quot;<br><br>if string1 === string2 {<br>  print(&quot;Strings are identical&quot;)<br>} // Won&#39;t print, strings are separate instances (literals are optimized)<br><br>// Same custom struct as before<br>let pointReference1 = point1<br>let pointReference2 = point1<br><br>if pointReference1 === pointReference2 {<br>  print(&quot;Points are identical&quot;) // Prints &quot;Points are identical&quot; (same object reference)<br>}</pre><p><strong>Key Differences:</strong></p><ul><li>== compares the values of objects, while === compares their memory addresses.</li><li>== is generally used for value comparison, while === is used for specific cases where you need to check if two variables refer to the exact same object instance.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879c3db8d016" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/vs-in-swift-879c3db8d016">== vs === in Swift</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lifecycle in iOS]]></title>
            <link>https://blog.stackademic.com/lifecycle-in-ios-0a045dea278c?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a045dea278c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 06:17:13 GMT</pubDate>
            <atom:updated>2024-04-23T06:17:13.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mMYt57-ZLE6Rz2hv" /></figure><p><strong>Have you ever wondered what happens when you tap an app icon on your iPhone? It seems like a simple act, but a fascinating story unfolds behind the scenes. This story is called the application lifecycle, and it dictates how an app transitions between different states, from its grand entrance to its graceful exit. Understanding this lifecycle is like learning the secret language of apps, empowering you to craft exceptional iOS experiences.</strong></p><h4><strong>The Enchanting Boot Up: The OS Takes the Stage</strong></h4><p>Imagine a grand theater. As you power on your iPhone, the core operating system software, the ever-present stage manager, springs to life. This includes SpringBoard, the maestro responsible for the home screen experience, launching apps, and even configuring some startup settings.</p><h4><strong>The Tapped Icon: SpringBoard Sets the Stage</strong></h4><p>The moment you tap an app icon, SpringBoard swiftly swings into action. It first sets the mood with an exciting animation of your app’s launch screen. But the real magic happens simultaneously: SpringBoard whisks your app and its essential shared libraries (reusable code components) onto the device’s memory, ensuring everything is readily available for the performance to begin.</p><h4><strong>Enter the AppDelegate: The App’s Guiding Light</strong></h4><p>With the app and libraries loaded, the spotlight shines on the AppDelegate, your app’s very own control center. Think of it as the stage director, responsible for managing the app’s lifecycle and responding to system cues.</p><h4><strong>The Power of Protocols: Granting Authority</strong></h4><p>But how does the AppDelegate wield such power? Here’s where protocols come in. The AppDelegate inherits from the UIResponder class, granting it the ability to respond to user interactions like taps or swipes. However, the real game-changer is the UIApplicationDelegate protocol. This protocol acts as a contract, outlining specific methods the AppDelegate must implement. By fulfilling these methods, the AppDelegate becomes the official director, gaining the authority to manage and react to various app lifecycle events.</p><h4><strong>A Symphony of Notifications: The AppDelegate Takes Control</strong></h4><p>So, what kind of events does the AppDelegate handle? Imagine it as the central nervous system, receiving vital notifications from the system. Here are some key moments the AppDelegate directs:</p><ul><li><strong>App Launch:</strong> The user taps the icon, and the AppDelegate receives a notification to initialize the app and prepare the user interface, raising the curtain on the show.</li><li><strong>Background/Foreground Transitions:</strong> When the app goes backstage (minimized or another app takes center stage) or returns to the spotlight, the AppDelegate is notified to manage resource usage accordingly.</li><li><strong>App Termination:</strong> If the system needs to free up memory or the user forcefully closes the app, the AppDelegate is informed so it can perform any necessary cleanup tasks, ensuring a smooth closing act.</li><li><strong>Push Notification Reception:</strong> If your app supports push notifications, the AppDelegate plays a crucial role in receiving and handling those notifications, potentially even launching specific app screens in response.</li></ul><p>By implementing these methods and responding to system notifications thoughtfully, the AppDelegate ensures your app launches smoothly, functions efficiently, and gracefully handles various user interactions and system events. So, the next time you launch an app, remember the intricate collaboration between the OS, SpringBoard, and your app’s diligent AppDelegate — a true backstage masterpiece.</p><h4><strong>The App’s Stage Appearances:</strong></h4><p>The application lifecycle dictates how an app behaves in different situations, just like actors on a stage. Let’s delve into how each state is used:</p><ul><li><strong>Not Running (Offstage):</strong> This is the initial state before the app is launched or after it’s been terminated. The app is simply waiting for its cue to appear on the stage.</li><li><strong>Inactive (Dimmed Lighting):</strong> The app is in the foreground but isn’t actively receiving events. Imagine the app is onstage but dimmed, perhaps waiting for another app’s scene to finish (like a pop-up dialog).</li><li><strong>Active (Spotlight):</strong> This is where the app shines! It’s in the foreground and has full user interaction. The system routes events (touches, gestures, etc.) to the app, and it can perform unrestricted actions, like network calls or animations, to keep the audience engaged.</li><li><strong>Background (Backstage):</strong> The app is still running but isn’t visible to the user. It has limited functionality and can only perform background tasks like location updates or audio playback (with limitations). Think of the app as backstage, working on some technical aspects while the main performance continues. The system can suspend the app at any time to conserve resources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DsiQZlz3b9nxhmPV.png" /></figure><h4><strong>Practical Examples in Action: Code Snippets for Key Events</strong></h4><p>Now, let’s see the application lifecycle in action with some code snippets from the AppDelegate:</p><h4><strong>AppDelegate:</strong></h4><ul><li>application(_:didFinishLaunchingWithOptions:) (Not Running -&gt; Inactive): <br>This method is called when the app launches. It&#39;s typically used to perform initial setup tasks like creating the main window, setting the root view controller (the main screen of your app), and potentially loading data.</li></ul><pre>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>    // Create the main window<br>    window = UIWindow(frame: UIScreen.main.bounds)<br><br>    // Set the root view controller (e.g., from storyboard)<br>    if let rootViewController = storyboard?.instantiateInitialViewController() {<br>        window?.rootViewController = rootViewController<br>    }<br><br>    window?.makeKeyAndVisible()<br>    return true<br>}</pre><ul><li>applicationWillEnterForeground(_:) (Background -&gt; Inactive -&gt; Active):<br>This method is called when the app is about to enter the foreground from the background state. It&#39;s a good place to refresh data, update the UI, or perform any tasks that need to be done before the app becomes fully active.</li></ul><pre>func applicationWillEnterForeground(_ application: UIApplication) {<br>    // Refresh data or perform tasks before app becomes active<br>}</pre><ul><li>applicationDidEnterBackground(_:) (Active -&gt; Inactive -&gt; Background):<br>This method is called when the app enters the background from the active state. It&#39;s crucial to use this method to save app data, pause ongoing tasks, and release unnecessary resources to conserve battery and avoid performance issues.</li></ul><pre>func applicationDidEnterBackground(_ application: UIApplication) {<br>    // Save app data, pause tasks, release resources<br>}</pre><ul><li>applicationWillTerminate(_:) (Any State -&gt; Not Running): This method (not shown in the image) is called when the app is about to terminate. It’s rarely used in practice, but you could potentially save critical data here if absolutely necessary. However, keep in mind that the system may terminate the app at any time and may not allow this method to complete.</li></ul><h4><strong>SceneDelegate (iOS 13 and later):</strong></h4><p>The SceneDelegate manages the lifecycle of individual scenes within your app (introduced in iOS 13). Here are some key methods:</p><ul><li>scene(_:willConnectTo:options:) (Not Running -&gt; Inactive): <br>This method is called when a scene is about to connect to a window. It&#39;s used to configure and create a new scene, typically involving setting up the view controller hierarchy and potentially restoring scene state from storage.</li></ul><pre>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>  // Create and configure a new scene (e.g., set up view controllers, window)<br>}</pre><ul><li>sceneDidDisconnect(_:) (Any State -&gt; Not Running):<br> This method is called when a scene disconnects from a window. It can be used for cleanup tasks, such as releasing resources associated with the scene.</li></ul><pre>func sceneDidDisconnect(_ scene: UIScene) {<br>  // Perform cleanup tasks when scene disconnects<br>}</pre><ul><li>sceneDidBecomeActive(_:)(Any State -&gt; Active): <br>This method (not shown in the image) is called when a scene becomes active. It’s similar to applicationWillEnterForeground(_:) in AppDelegate but specific to a scene.</li><li>sceneWillEnterForeground(_:) (Background -&gt; Inactive -&gt; Active):<br> This method (not shown in the image) is called when a scene is about to enter the foreground from the background state. It’s similar to applicationWillEnterForeground(_:) in AppDelegate but specific to a scene.</li><li>sceneDidEnterForeground(_:) (Active -&gt; Inactive -&gt; Background):<br> This method (not shown in the image) is called when a scene enters the background from the active state. It’s similar to applicationDidEnterBackground(_:) in AppDelegate but specific to a scene.</li></ul><h4><strong>Additional Considerations for Expert Developers</strong></h4><p>While the basic lifecycle events are covered, here are some additional points to consider for a more comprehensive understanding:</p><ul><li><strong>Error Handling and Unexpected Transitions:</strong> The article primarily focuses on ideal scenarios. In the real world, errors or unexpected lifecycle transitions can occur (e.g., system termination without calling applicationWillTerminate(_:)). Developers should implement appropriate error handling and recovery mechanisms to ensure a graceful user experience.</li><li><strong>Memory Warnings:</strong> iOS can notify your app when memory is running low. The applicationDidReceiveMemoryWarning(_:) method within the AppDelegate can be used to respond to these warnings by releasing unnecessary resources or taking other actions to reduce the app&#39;s memory footprint.</li><li><strong>State Restoration:</strong> When transitioning to the background, apps can save their current state (e.g., view controller state, user data) using techniques like NSCoding or Codable. The system can then attempt to restore this state when the app returns to the foreground, providing a seamless user experience.</li><li><strong>Advanced Background Modes:</strong> While background execution is limited, iOS offers advanced background modes like Voip (Voice over IP) for continuous audio communication or background fetch for periodically updating app content. Understanding these modes can help developers create more powerful features.</li></ul><h3>Finally :</h3><p>By understanding the application life cycle, developers can create exceptional iOS apps that are efficient, user-friendly, and adaptable to various situations. This knowledge empowers them to design apps that are both powerful and considerate of system resources.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a045dea278c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lifecycle-in-ios-0a045dea278c">Lifecycle in iOS</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Swift: Full Guide]]></title>
            <link>https://blog.stackademic.com/generics-in-swift-full-guide-6a42284ef926?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a42284ef926</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[generics-in-swift]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 04:16:53 GMT</pubDate>
            <atom:updated>2023-11-21T04:16:53.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UsW8tT-7zlbFxSNr" /></figure><p>Generics are a powerful tool that can transform your Swift code from ordinary to extraordinary. With generics, you can write code that is flexible, reusable, and type-safe, making your code more maintainable, expressive, and efficient.</p><h3>What is the Problem that Generic Solve?</h3><p>In programming, it&#39;s common to write code that manipulates data of different types. For instance, you might need to swap the values of two integers, swap the values of two strings, or swap the values of two doubles. Without generics, you would need to write a separate function for each type of data:</p><pre>func swapTwoInts(_ a: inout Int, _ b: inout Int) {<br>  let temp = a<br>  a = b<br>  b = temp<br>}<br><br>func swapTwoStrings(_ a: inout String, _ b: inout String) {<br>  let temp = a<br>  a = b<br>  b = temp<br>}<br><br>func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {<br>  let temp = a<br>  a = b<br>  b = temp<br>}</pre><blockquote>This approach is repetitive and error-prone, as you need to write a separate function for each type you want to swap. Additionally, it makes the code less maintainable, as you need to modify multiple functions if you want to change the swapping logic.</blockquote><h4>Generics to the Rescue</h4><p>Generics provide a solution to the problem of type repetition by allowing you to write code that can work with any type. This is achieved by using placeholders, represented by type parameters, which serve as placeholders for actual types. For example, you can define a generic swap function that can work with any type:</p><pre>func swap&lt;T&gt;(a: inout T, b: inout T) {<br>  let temp = a<br>  a = b<br>  b = temp<br>}</pre><blockquote>In this code, T is a type parameter that represents the type of the values being swapped. This means that the swap function can be used to swap integers, strings, doubles, or any other type.</blockquote><h3>Declaring Generic Types</h3><h4>1. Declaring Generic Types:</h4><p>To declare a generic type, you use the &lt;T&gt; syntax after the type name. For example, the following code declares a generic class called Box that can hold a value of any type:</p><pre>public class Box&lt;T&gt; {<br>    var value: T<br>}</pre><p>In this example, T is the type parameter, which represents the type of value that the Box can hold. When you create an instance of Box, you must specify the actual type of the value you want to store. For example, the following code creates an instance of Box that holds an integer value:</p><pre>let intBox = Box&lt;Int&gt;(value: 10)</pre><p>Similarly, you can create instances of Box that hold string values, float values, or any other type.</p><h4>2. Declaring Generic Functions:</h4><p>Generic functions are declared similarly to generic types, using the &lt;T&gt; syntax after the function name. For example, the following code declares a generic function called swap that swaps two values of any type:</p><pre>func swap&lt;T&gt;(_ a: T, _ b: T) {<br>    var temp = a<br>    a = b<br>    b = temp<br>}</pre><p>This function can be called with any pair of values of the same type. For example, the following code swaps two integer values:</p><pre>swap(10, 20)</pre><h4>3. Declaring Generic Methods:</h4><p>Generic methods are declared on types rather than on top-level code. For example, the following code declares a generic method called swapTwoElements on the Array type:</p><pre>extension Array {<br>    mutating func swapTwoElements(_ i: Int, _ j: Int) {<br>        if i &gt;= 0 &amp;&amp; i &lt; count &amp;&amp; j &gt;= 0 &amp;&amp; j &lt; count {<br>            var temp = self[i]<br>            self[i] = self[j]<br>            self[j] = temp<br>        }<br>    }<br>}</pre><p>This method can be called on any instance of Array, regardless of the element type. For example, the following code swaps two elements in an array of strings:</p><pre>var names = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>names.swapTwoElements(0, 2)<br>print(names) // Output: [&quot;Charlie&quot;, &quot;Bob&quot;, &quot;Alice&quot;]</pre><h4>4. Declaring Generic Enums:</h4><p>Generic enums allow you to define enum cases that can hold values of different types. For example, you could create a generic enum for storing different types of measurements:</p><pre>enum Measurement&lt;Unit&gt; {<br>    case length(value: Double)<br>    case volume(value: Double)<br>    case weight(value: Double)<br>}</pre><p>In this example, Unit is the type parameter, representing the type of unit for the measurement. When you create an instance of Measurement, you must specify the type of unit and the corresponding value. For instance, the following code creates an instance of Measurement representing 10 meters:</p><pre>let distance: Measurement&lt;Meter&gt; = .length(value: 10)</pre><p>Similarly, you can create instances of Measurement for volumes, weights, or any other type you define.</p><h4>5. Declaring Generic Structs:</h4><p>Generic structs allow you to define structs that can hold values of different types. For example, you could create a generic struct for representing different types of shapes:</p><pre>struct Shape&lt;T: Numeric&gt; {<br>    let center: Point<br>    let dimensions: (T, T)<br>}</pre><p>In this example, T is the type parameter, representing the type of numeric value used for the shape&#39;s dimensions. This allows you to create shapes with integer, float, or any other numeric type. For instance, the following code creates a square with integer dimensions:</p><pre>let square = Shape(center: Point(x: 0, y: 0), dimensions: (5, 5))</pre><p>Similarly, you can create shapes with different dimensions and numeric types.</p><h3>Using Generics in real-world Swift applications:</h3><p>some practical examples of how generics are used in real-world Swift applications:</p><h4>1. Networking:</h4><p>There are a few different ways to use generics in networking in iOS. One common approach is to use a generic networking library, such as Alamofire or Moya. These libraries provide a unified interface for making HTTP requests and handling responses, regardless of the specific data type being exchanged.</p><p>For example, the following code shows how to use Alamofire to make a GET request to a JSON API and decode the response into a struct of type Post:</p><pre>import Alamofire<br><br>AF.request(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;)<br>    .responseDecodable(of: Post.self) { response in<br>        if let post = response.value {<br>            print(post.title)<br>            print(post.body)<br>        } else {<br>            print(&quot;Error decoding JSON response&quot;)<br>        }<br>    }</pre><p>Another way to use generics in networking is to write your own generic networking code. This can be a bit more complex, but it gives you more control over the networking process.</p><p>Here is an example of how to write a generic function for making a GET request and decoding the response into a JSON object:</p><pre>func getJSON&lt;T: Decodable&gt;(url: URL) async throws -&gt; T {<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return try JSONDecoder().decode(T.self, from: data)<br>}</pre><p>This function can be used to make a GET request to any URL and decode the response into a JSON object of type T. For example, the following code shows how to use the function to make a request to the JSONPlaceholder API:</p><pre>let post: Post = try await getJSON(url: URL(string: &quot;https://jsonplaceholder.typicode.com/posts/1&quot;)!)<br>print(post.title)<br>print(post.body)</pre><h4>2. Data Storage:</h4><p>There are a few different ways to use generics in data storage in iOS. One common approach is to use a generic data storage library, such as Realm or CoreData. These libraries provide a unified interface for storing and retrieving data, regardless of the specific data type being stored.</p><h4><strong>Here are a few examples of popular generic data storage libraries for iOS:</strong></h4><h4><strong>- Realm:</strong></h4><p>Realm is a high-performance mobile database that is based on Realm Core, a cross-platform object-relational mapping (ORM) framework. Realm is known for its speed and ease of use.<br>Realm provides a number of generic methods for storing and retrieving data. For example, the following code shows how to store a Post object in Realm:</p><pre>let realm = try! Realm()<br>let post = Post()<br>post.id = 1<br>post.title = &quot;My First Post&quot;<br>post.body = &quot;This is the content of my first post.&quot;<br><br>try! realm.add(post)</pre><p>This code will store the post object in Realm. The add() method is a generic method that can be used to store any object that conforms to the Object protocol.</p><h4>- CoreData:</h4><p>CoreData is a built-in data storage framework that is part of the iOS SDK. CoreData is a powerful and flexible framework, but it can be more complex to use than Realm.</p><p>CoreData provides a number of generic methods for storing and retrieving data. For example, the following code shows how to fetch all of the Post objects from CoreData:</p><pre>let fetchRequest = NSFetchRequest&lt;NSManagedObject&gt;(entityName: &quot;Post&quot;)<br>let posts = try! context.fetch(fetchRequest)</pre><p>This code will fetch all of the Post objects from the Post entity in CoreData. The fetchRequest is a generic fetch request that can be used to fetch any object from any entity.</p><h4>3. View Models:</h4><p>View models play a crucial role in MVVM (Model-View-ViewModel) architecture, acting as a bridge between the data model and the user interface. Generics, a powerful feature of Swift, can significantly enhance the flexibility and type safety of view models in iOS applications.</p><p>Consider a generic view model BaseViewModel&lt;T&gt;, where T represents the data model type:</p><pre>class BaseViewModel&lt;T&gt; {<br>    private var dataModel: T?<br><br>    func updateData(with dataModel: T) {<br>        self.dataModel = dataModel<br>    }<br><br>    func getDataModel() -&gt; T? {<br>        return dataModel<br>    }<br>}</pre><p>This generic view model can be used with any data model type by specifying the concrete type when creating an instance:</p><pre>let postViewModel = BaseViewModel&lt;Post&gt;()</pre><p>This instance of BaseViewModel can now handle data of type Post.</p><h4><strong>Extending Generic ViewModels:</strong></h4><p>Generic view models can be extended to provide specific functionality for different data types. For example, a PostViewModel subclass can inherit from BaseViewModel&lt;Post&gt; and add methods specific to Post data:</p><pre>class PostViewModel: BaseViewModel&lt;Post&gt; {<br>    func getAuthorName() -&gt; String? {<br>        return dataModel?.author<br>    }<br>}</pre><p>This approach allows for specialized functionality while maintaining the reusability of the generic base view model.</p><h4><strong>Generic ViewModels in Real-world Scenarios:</strong></h4><p>Generic view models are particularly useful in scenarios where you deal with multiple data types, such as managing a list of different items or displaying data from various sources.</p><p>Consider a list of items in an e-commerce application. Each item can be of a different type (product, category, promotion), but the view model responsible for managing the list should be able to handle these different types seamlessly.</p><p>A generic view model can be used to manage the list, providing methods for adding, removing, and accessing items, regardless of their specific type. This approach promotes code reuse and reduces the complexity of handling multiple data types.</p><h4>Generic ViewModels in Real-world Scenarios</h4><p>Generic view models are particularly useful in scenarios where you deal with multiple data types, such as managing a list of different items or displaying data from various sources.</p><p>Consider a list of items in an e-commerce application. Each item can be of a different type (product, category, promotion), but the view model responsible for managing the list should be able to handle these different types seamlessly.</p><p>A generic view model can be used to manage the list, providing methods for adding, removing, and accessing items, regardless of their specific type. This approach promotes code reuse and reduces the complexity of handling multiple data types.</p><h4>4. Custom Collections:</h4><p>Generic custom collections, such as linked lists and stacks, use generics to store and manage elements of different types. This provides a flexible and reusable way to organize and manipulate data.</p><pre>struct Stack&lt;T&gt; {<br>    private var elements: [T] = []<br><br>    mutating func push(_ element: T) {<br>        elements.append(element)<br>    }<br><br>    mutating func pop() -&gt; T? {<br>        return elements.popLast()<br>    }<br>}</pre><h4>5. Utility Functions:</h4><p>Generic utility functions, such as sorting and filtering algorithms, use generics to operate on data of different types. This promotes code reuse and avoids the need for type-specific implementations.</p><pre>func sort&lt;T: Comparable&gt;(_ collection: [T]) -&gt; [T] {<br>    return collection.sorted()<br>}<br><br>func filter&lt;T: Equatable&gt;(_ collection: [T], predicate: (T) -&gt; Bool) -&gt; [T] {<br>    return collection.filter(predicate)<br>}</pre><h3>Benefits of Generics:</h3><ul><li>Type safety: Generics ensure that the code is type-safe, as the compiler checks whether the types used with a generic function or type are compatible.</li><li>Code reusability: Generics allow you to write code that can be reused with different data types, reducing code duplication and improving maintainability.</li><li>Expressive code: Generics enable you to write code that is more concise and expressive, as it captures the general logic without being tied to a specific type.</li></ul><h3>Finally:</h3><ul><li>Generics are a powerful feature of Swift that allows you to write code that can work with a variety of data types.</li><li>There are several benefits to using generics, including reusability, type safety, and readability.</li><li>Generics can be used in a variety of situations, including networking, data storage, and view models.</li></ul><h3>Stackademic:</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a42284ef926" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/generics-in-swift-full-guide-6a42284ef926">Generics in Swift: Full Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums in Swift: Full Guide]]></title>
            <link>https://blog.stackademic.com/enums-in-swift-full-guide-c4f3cacc88fd?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f3cacc88fd</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 12:16:01 GMT</pubDate>
            <atom:updated>2023-11-10T12:16:01.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*5yU7h8bYxavRU9v_" /></figure><p><strong>Enums</strong> are a powerful data type in Swift. They can be used to represent a wide variety of concepts, from simple states and conditions to complex data structures. Enums can also be used to make your code more readable, maintainable, and type-safe.</p><h3>Example 1:</h3><p>Imagine a restaurant. The menu has a variety of different dishes, each of which belongs to a specific category, such as appetizers, main courses, and desserts.</p><p>An enum in Swift is like a menu category. It defines a set of related values, each of which represents a different option within that category. For example, an enum to represent the different types of main courses could have the following cases:</p><ul><li>pasta</li><li>pizza</li><li>burger</li><li>steak</li></ul><p>Each case in the enum can have its own associated value, if needed. For example, the pasta case could have an associated value to represent the specific type of pasta dish, such as spaghetti or lasagna.</p><h3>How to define an enum?</h3><p>To define an enum in Swift, use the enum keyword followed by the name of the enum and a list of its cases. Each case can have its own associated value, which can be any type of data.</p><p>For example, Let’s say you’re developing an iOS app for a clothing store. You could use an enum to represent the different types of clothing that the store sells, such as:</p><pre>enum ClothingType {<br>    case shirts<br>    case pants<br>    case dresses<br>    case shoes<br>    case accessories<br>}</pre><p>You could then use this enum to declare variables to store the type of clothing that a customer is interested in. For example:</p><pre>var selectedClothingType: ClothingType = .shirts</pre><p>You could also use the enum in a switch statement to display different product categories to the user, depending on the selected clothing type.</p><pre>switch selectedClothingType {<br>case .shirts:<br>    // Display shirts.<br>case .pants:<br>    // Display pants.<br>case .dresses:<br>    // Display dresses.<br>case .shoes:<br>    // Display shoes.<br>case .accessories:<br>    // Display accessories.<br>}</pre><p>By using an enum to represent the different types of clothing, you can make your code more readable, maintainable, and type-safe.</p><h3>Types of Enum:</h3><h4>1- Value enums:</h4><p>Value enums are the simplest type of enum. They define a list of related values, but they do not store any additional data.</p><p><strong>Example of value enums:</strong></p><pre>enum DayOfWeek {<br>  case sunday<br>  case monday<br>  case tuesday<br>  case wednesday<br>  case thursday<br>  case friday<br>  case saturday<br>}</pre><p>To create an instance of a value enum, you simply assign it to a variable or constant. For example:</p><pre>let dayOfWeek = DayOfWeek.monday<br>print(dayOfWeek) // Prints &quot;monday&quot;</pre><h4>2- Raw value enums:</h4><p>Raw value enums are a type of enum that allows you to associate a raw value with each enum case. The raw value can be any type of data, such as an integer, string, or character.</p><p><strong>Example of Raw value enums:</strong></p><pre>enum FileExtension: String {<br>  case jpg = &quot;jpg&quot;<br>  case png = &quot;png&quot;<br>  case gif = &quot;gif&quot;<br>  case pdf = &quot;pdf&quot;<br>}</pre><p>To create an instance of a raw value enum, you simply pass the raw value to the initializer. For example:</p><pre>let fileExtenision = FileExtension(rawValue: &quot;jpg&quot;)</pre><p>You can then use the instance to access the raw value. For example:</p><pre>print(fileExtenision.rawValue) // Prints &quot;jpg&quot;</pre><h4>3- Associated value enums:</h4><p>Associated value enums are a type of enum that allows you to store additional data with each enum case. This can be useful for representing complex data structures or relationships.</p><p><strong>Example of Associated value enums:</strong></p><pre>enum UserInfo {<br>  case name(String)<br>  case emailAddress(String)<br>  case phoneNumber(String)<br>}</pre><p>To create an instance of an associated value enum, you simply pass the associated value to the initializer. For example:</p><pre>let userInfo = UserInfo.emailAddress(&quot;john.doe@example.com&quot;)</pre><p>You can then use the instance to access the associated value. For example:</p><pre>print(userInfo.emailAddress) // Prints &quot;john.doe@example.com&quot;</pre><h3>Using enums in your code:</h3><h4>1- How to use enums in switch statements?</h4><p>To use enums in switch statements in Swift, you simply pass the enum case to the switch statement. The switch statement will then match the enum case to one of the cases in the statement body.</p><p>For example, the following code uses to Calculating the discount for a customer based on their membership level:</p><pre>enum MembershipLevel {<br>  GOLD,<br>  SILVER,<br>  BRONZE<br>}<br><br>MembershipLevel membershipLevel = MembershipLevel.SILVER;<br>double price = 100.00;<br><br>switch (membershipLevel) {<br>  case GOLD:<br>    double discount = price * 0.20;<br>    price -= discount;<br>    System.out.println(&quot;Your new price is: $&quot; + price);<br>    break;<br>  case SILVER:<br>    discount = price * 0.10;<br>    price -= discount;<br>    System.out.println(&quot;Your new price is: $&quot; + price);<br>    break;<br>  case BRONZE:<br>    discount = price * 0.05;<br>    price -= discount;<br>    System.out.println(&quot;Your new price is: $&quot; + price);<br>    break;<br>}</pre><p>This code uses a switch statement to apply a discount to the price based on the value of the membershipLevel variable. The switch statement evaluates the value of membershipLevel and executes the code block that corresponds to the matching case. In this case, the code block for the SILVER case is executed, which calculates a discount of 10% and applies it to the price. The break statement is used to exit the switch statement after each case has been executed.</p><p>You can also use associated values in switch statements. you could create an enum that represents different types of airplanes and store the maximum number of passengers for each type of airplane.</p><pre>enum AirplaneType {<br>  case Boeing747(maxPassengers: 416)<br>  case AirbusA380(maxPassengers: 853)<br>  case Boeing777(maxPassengers: 400)<br>}<br><br>let airplaneType: AirplaneType = .Boeing747<br>let maxPassengers: Int<br><br>switch airplaneType {<br>case .Boeing747(let numPassengers):<br>  maxPassengers = numPassengers<br>case .AirbusA380(let numPassengers):<br>  maxPassengers = numPassengers<br>case .Boeing777(let numPassengers):<br>  maxPassengers = numPassengers<br>}<br><br>print(&quot;The maximum number of passengers for this airplane is \(maxPassengers).&quot;)</pre><p>You can then use a switch statement to handle the different airplane types and access the associated values.</p><p>This code will print “The maximum number of passengers for this airplane is 416.”</p><p>Associated values can be used to store any type of data, including strings, numbers, and even other enums. They can be a powerful way to add more flexibility and expressiveness to your Swift code.</p><h4>2- How to use enums to validate data?</h4><p>To use enums to validate data in Swift, you can use a switch statement to check the value of the enum case. If the enum case is not valid, you can throw an error or take some other corrective action.</p><p>simple example:</p><pre>enum ValidationError: Error {<br>  case emptyName<br>  case invalidEmailAddress<br>  case invalidPhoneNumber<br>}<br><br>func validateUser(name: String, emailAddress: String, phoneNumber: String) throws {<br>  if name.isEmpty {<br>    throw ValidationError.emptyName<br>  }<br><br>  if !emailAddress.isValidEmailAddress {<br>    throw ValidationError.invalidEmailAddress<br>  }<br><br>  if !phoneNumber.isValidPhoneNumber {<br>    throw ValidationError.invalidPhoneNumber<br>  }<br>}<br><br>// Example usage:<br><br>do {<br>  try validateUser(name: &quot;John Doe&quot;, emailAddress: &quot;john.doe@example.com&quot;, phoneNumber: &quot;+15555555555&quot;)<br>} catch let error {<br>  // Handle the validation error.<br>  print(error)<br>}</pre><p>This code uses an enum to represent different types of validation errors. The validateUser() function takes a user&#39;s name, email address, and phone number as input and validates them. The function uses a switch statement to handle the different cases. If the validation fails, the function throws the appropriate validation error.</p><h4>3- How to use enums to represent different states of a system?</h4><p>To use enums to represent different states of a system in Swift, you can define an enum with a case for each state. You can then use the enum to track the current state of the system and to transition between states.</p><p>For example, the following code defines an enum to represent the different states of a loading bar:</p><pre>enum LoadingState {<br>  case notStarted<br>  case loading<br>  case finished<br>}</pre><p>This enum has three cases: notStarted, loading, and finished. You can use this enum to keep track of the current state of the loading bar and to transition between states. For example, the following code shows how to start the loading bar and then transition to the finished state when the loading is complete:</p><pre>var loadingState = LoadingState.notStarted<br><br>func startLoading() {<br>  loadingState = .loading<br>}<br><br>func finishLoading() {<br>  loadingState = .finished<br>}</pre><p>You can also use the enum to make decisions about what to do based on the current state of the system. For example, the following code shows how to only enable a button if the loading bar is finished:</p><pre>var loadingState = LoadingState.notStarted<br><br>func enableButton() {<br>  if loadingState == .finished {<br>    // Enable the button.<br>  }<br>}</pre><p>Using enums to represent different states of a system can help you to write more modular and reusable code. By encapsulating the state of the system in an enum, you can make your code easier to read and maintain.</p><p>Here is another example of using an enum to represent different states of a system:</p><pre>enum TrafficLightState {<br>  case red<br>  case yellow<br>  case green<br>}<br><br>class TrafficLight {<br>  private var state: TrafficLightState = .red<br><br>  func nextState() {<br>    switch state {<br>    case .red:<br>      state = .green<br>    case .green:<br>      state = .yellow<br>    case .yellow:<br>      state = .red<br>    }<br>  }<br><br>  func currentState() -&gt; TrafficLightState {<br>    return state<br>  }<br>}</pre><p>This code defines a TrafficLight class that uses an enum to represent the different states of the traffic light. The class has a nextState() method that transitions the traffic light to the next state, and a currentState() method that returns the current state of the traffic light.</p><p>You could use this class in a traffic light simulation or in a game to control the state of the traffic light. For example, the following code shows how to simulate a traffic light that changes states every 5 seconds:</p><pre>let trafficLight = TrafficLight()<br><br>while true {<br>  // Wait for 5 seconds.<br>  Thread.sleep(forTimeInterval: 5)<br><br>  // Transition to the next state.<br>  trafficLight.nextState()<br><br>  // Print the current state of the traffic light.<br>  print(trafficLight.currentState())<br>}</pre><p>This code will print the following output to the console:</p><pre>red<br>green<br>yellow<br>red<br>green<br>yellow</pre><h4>4- How to create custom operators for enums?</h4><p><strong>What are custom operators?<br></strong>Custom operators are user-defined symbols that perform specific operations on data types. They’re like shortcuts that make your code more concise and readable. For example, you could create a custom operator called + for the Season enum that adds two seasons together:</p><pre>infix operator +<br>func + (lhs: Season, rhs: Season) -&gt; Season {<br>    if lhs == .winter &amp;&amp; rhs == .spring {<br>        return .summer<br>    } else {<br>        return .error<br>    }<br>}</pre><p><strong>To create a custom operator for an enum</strong>, you need to specify its type and define a function that performs the desired operation. The function’s name should match the operator symbol, and its arguments and return type should match the data type being operated on.</p><p>Consider a class called ShoppingCart that keeps track of items being purchased. You could create a custom operator called ++ that adds an item to the cart:</p><pre>infix operator ++<br>func ++ (cart: ShoppingCart, item: Item) -&gt; ShoppingCart {<br>    return cart.addingItem(item)<br>}</pre><p>This operator would make it easy to add items to the cart using a concise syntax:</p><pre>let cart = ShoppingCart()<br>cart ++ Item(name: &quot;Apples&quot;, price: 1.99)<br>cart ++ Item(name: &quot;Oranges&quot;, price: 2.99)</pre><h3>Now we will move to advance concepts by enum &gt;</h3><h3>Pattern matching:</h3><p>Pattern matching allows you to compare the value of an expression to a series of patterns. If the value of the expression matches a pattern, the code in the corresponding case block is executed. Otherwise, the next pattern is matched. If none of the patterns match, the default case is executed.</p><p>Enums are a way to represent a group of related values. For example, you could use an enum to represent the different states of a traffic light (red, yellow, green) or the different types of errors that your code could throw.</p><p>One common use case for pattern matching enums is to handle different types of errors. For example, the following code uses pattern matching to handle different types of network errors:</p><pre>enum NetworkError: Error {<br>  case badRequest<br>  case unauthorized<br>  case internalServerError<br>}<br><br>func makeNetworkRequest() throws -&gt; Data {<br>  // Make the network request.<br><br>  // Handle the response.<br>  switch response.statusCode {<br>  case 200:<br>    return response.data<br>  case 400:<br>    throw NetworkError.badRequest<br>  case 401:<br>    throw NetworkError.unauthorized<br>  case 500:<br>    throw NetworkError.internalServerError<br>  default:<br>    throw NetworkError.unknown<br>  }<br>}</pre><p>This code will match the status code of the network response to one of the cases in the NetworkError enum. If the status code is 200, the code will return the data from the response. Otherwise, the code will throw the appropriate error.</p><h3>Associated Types:</h3><p>Associated types are a powerful feature of Swift that allow you to create enums that can work with different types of data. This can be useful for representing complex data structures, relationships, and errors.</p><p>associated type is a placeholder for a type that will be specified when the enum is used. This means that you can define an enum without knowing the specific types of data that it will be used to represent.</p><p>For example, the following enum represents the result of an operation that can either succeed or fail:</p><pre>enum Result&lt;T, E&gt; {<br>  case success(T)<br>  case failure(E)<br>}</pre><p>The Result enum has two associated types: T and E. The T type represents the type of data that the operation can succeed with. The E type represents the type of error that the operation can fail with.</p><h4>When to use associated types?</h4><p>You should use associated types when you need to create an enum that can work with different types of data. For example, you might use associated types to represent the result of an operation, the different states of a system, or the different types of data that a function can accept.</p><p>example about how to use associated types with enums:</p><pre>enum HTTPStatusCode: Int {<br>  case ok = 200<br>  case badRequest = 400<br>  case internalServerError = 500<br>}<br><br>enum HTTPError: Error {<br>  case badRequest<br>  case internalServerError<br>}<br><br>func makeRequest(to url: URL, completion: @escaping (Result&lt;Data, HTTPError&gt;) -&gt; Void) {<br>  // Make the request.<br><br>  // Handle the response.<br>  switch response.statusCode {<br>  case HTTPStatusCode.ok:<br>    completion(.success(response.data))<br>  case HTTPStatusCode.badRequest:<br>    completion(.failure(.badRequest))<br>  case HTTPStatusCode.internalServerError:<br>    completion(.failure(.internalServerError))<br>  default:<br>    completion(.failure(.unknown))<br>  }<br>}</pre><p>The makeRequest() function uses associated types to represent the result of the request. The function can either succeed with Data or fail with HTTPError.</p><p>The caller of the makeRequest() function can use pattern matching to handle the different cases of the result. For example, the following code handles the success case:</p><pre>makeRequest(to: url) { result in<br>  switch result {<br>  case .success(let data):<br>    // Handle the data.<br>  case .failure(let error):<br>    // Handle the error.<br>  }<br>}</pre><h3>Popular cases to use enum as iOS developer:</h3><h3>1- Use Enums to Represent Different Types of Errors:</h3><p>Enums are a powerful tool for representing different types of errors in Swift. By using enums, you can create a more robust and informative error handling system.</p><h4>Case 1: Network errors</h4><p>One common use case for enums to represent errors is network errors. The following enum represents different types of network errors:</p><pre>enum NetworkError: Error {<br>  case badRequest<br>  case unauthorized<br>  case internalServerError<br>  case unknown<br>}</pre><p>You can use this enum to represent the different types of errors that can occur when making a network request. For example, the following code shows how to make a network request and handle different types of network errors:</p><pre>func makeNetworkRequest() throws -&gt; Data {<br>  // Make the network request.<br><br>  // Handle the response.<br>  switch response.statusCode {<br>  case 200:<br>    return response.data<br>  case 400:<br>    throw NetworkError.badRequest<br>  case 401:<br>    throw NetworkError.unauthorized<br>  case 500:<br>    throw NetworkError.internalServerError<br>  default:<br>    throw NetworkError.unknown<br>  }<br>}</pre><p>This code will throw the appropriate network error if the request fails. The caller of the makeNetworkRequest() function can then catch the error and handle it accordingly.</p><h4>Case 2: User input errors</h4><p>Another common use case for enums to represent errors is user input errors. The following enum represents different types of user input errors:</p><pre>enum UserInputError: Error {<br>  case emptyName<br>  case invalidEmailAddress<br>  case invalidPhoneNumber<br>}</pre><p>You can use this enum to represent the different types of errors that can occur when validating user input. For example, the following code shows how to validate a user’s name and email address:</p><pre>func validateUser(name: String, emailAddress: String) throws {<br>  if name.isEmpty {<br>    throw UserInputError.emptyName<br>  }<br><br>  if !emailAddress.isValidEmailAddress {<br>    throw UserInputError.invalidEmailAddress<br>  }<br>}</pre><p>This code will throw the appropriate user input error if the validation fails. The caller of the validateUser() function can then catch the error and handle it accordingly.</p><h4>Case 3: Custom errors</h4><p>You can also use enums to represent custom errors. For example, the following enum represents different types of errors that can occur when parsing a JSON file:</p><pre>enum JSONParsingError: Error {<br>  case invalidJSON<br>  case missingKey(String)<br>  case unexpectedValueType(String)<br>}</pre><p>You can use this enum to represent the different types of errors that can occur when parsing a JSON file. For example, the following code shows how to parse a JSON file and handle different types of JSON parsing errors:</p><pre>func parseJSONFile(at url: URL) throws -&gt; [String: Any] {<br>  // Read the JSON file.<br><br>  // Parse the JSON file.<br>  let data = try Data(contentsOf: url)<br>  do {<br>    let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]<br>    return json ?? [:]<br>  } catch {<br>    throw JSONParsingError.invalidJSON<br>  }<br>}</pre><p>This code will throw the appropriate JSON parsing error if the parsing fails. The caller of the parseJSONFile() function can then catch the error and handle it accordingly.</p><h3>2- Use enums to improve the readability and maintainability of your code:</h3><h4>Case study 1: Representing different types of data</h4><p>One common use case for enums is to represent different types of data. For example, the following enum represents different types of fruit:</p><pre>enum Fruit {<br>  case apple<br>  case banana<br>  case orange<br>  case mango<br>}</pre><p>This enum makes it clear and concise to represent different types of fruit in your code. Instead of using strings or constants, you can use the enum cases.</p><p>For example, the following code shows how to use the Fruit enum to create a variable that represents a banana:</p><pre>var favoriteFruit: Fruit = .banana</pre><p>This code is more readable and maintainable than using a string or constant, because it is clear what type of data the variable is representing.</p><h4>Case study 2: Representing different states of a system</h4><p>Another common use case for enums is to represent different states of a system. For example, the following enum represents the different states of a traffic light:</p><pre>enum TrafficLightState {<br>  case red<br>  case yellow<br>  case green<br>}</pre><p>This enum makes it clear and concise to represent the different states of a traffic light in your code. Instead of using strings or constants, you can use the enum cases.</p><p>For example, the following code shows how to use the TrafficLightState enum to create a variable that represents a traffic light that is currently red:</p><pre>var trafficLightState: TrafficLightState = .red</pre><p>This code is more readable and maintainable than using a string or constant, because it is clear what state the traffic light is currently in.</p><h3>Benefits of using enums:</h3><ul><li>Enums make your code more readable by providing a clear and concise way to represent different states, conditions, or data types.</li><li>Enums make your code more maintainable by reducing the risk of bugs. For example, if you use an enum to represent the different types of errors that a function can return, you can be sure that the function will always return a valid error code.</li><li>Enums help you to write type-safe code. For example, if you use an enum to represent the different types of data that a function can accept, you can be sure that the function will never be passed an invalid data type.</li></ul><h3>Finally:</h3><p>Enums are a useful tool that can make your Swift code more readable, maintainable, and type-safe. Use enums to represent related values, associated values to store additional data with each enum case, and pattern matching to implement complex logic in a concise and efficient way.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f3cacc88fd" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/enums-in-swift-full-guide-c4f3cacc88fd">Enums in Swift: Full Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adapter Design Pattern in iOS]]></title>
            <link>https://blog.stackademic.com/adapter-design-pattern-in-ios-9e008ec29414?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e008ec29414</guid>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 06:16:57 GMT</pubDate>
            <atom:updated>2023-11-07T06:16:57.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BKYMCWSKf55_SipU" /></figure><p>The Adapter design pattern is a structural design pattern that allows objects with incompatible interfaces to work together. It does this by creating a wrapper object that translates the interface of one object to the interface of another object.</p><p>The Adapter pattern is often used to integrate existing code into a new system, or to make two different frameworks work together. It can also be used to simplify the use of a complex class, by providing a simpler interface to it.</p><h3>Example 1: 👶</h3><p>Imagine You have a collection of old, printed photographs that you want to store digitally on your computer. However, your computer’s scanner only accepts digital images and cannot directly scan the printed photographs.<br>The problem here is the printed photographs (Adaptee) have an incompatible interface (physical form) with your computer’s scanner (Client), making it impossible to directly scan them.<br>For solve it You use a photo scanner adapter (Adapter) that can take the printed photographs and convert them into a digital format that your computer’s scanner can understand. The photo scanner adapter acts as a bridge between the printed photographs and the computer’s scanner, allowing you to store the images digitally.</p><h3>Example 2: 🍎</h3><p>Imagine you have a train track system with trains running on it. Each train has a specific type of engine: steam engines, electric motors, and magnetic field power. Each type of engine has a different way of starting and stopping.</p><p>Now, you want to introduce a new type of train with a different engine to the existing system. However, this new train has its own unique way of starting and stopping that doesn’t match the existing system’s expectations.</p><p>To solve this, you can use an adapter. In the train analogy, an adapter is like a device or mechanism that allows a train with a different engine to seamlessly fit into the existing system.</p><p>The adapter acts as an intermediary between the new train and the existing system, translating the commands expected by the system into the appropriate actions for the new train’s engine. It bridges the gap between the incompatible interfaces.</p><p>For example, let’s consider a scenario where the existing trains in the system are powered by steam engines, and the new train has a magnetic field power system. The existing system expects trains to start and stop using a lever mechanism, while the new train is controlled by a button.</p><p>The adapter, in this case, would be like a device that receives the “start” command from the lever mechanism and translates it into the appropriate action of pressing the button to power on the magnetic field. Similarly, when the lever mechanism sends the “stop” command, the adapter translates it into the action of pressing the button to power off the magnetic field.</p><p>By using the adapter, the new train with the magnetic field power system can seamlessly integrate into the existing train track system without requiring any modifications to the system itself. The adapter ensures compatibility between the different interfaces and allows the new train to be controlled and operated using the existing commands and mechanisms.</p><h3>The Adapter pattern has four main components:</h3><ul><li>Target: The interface that the client expects.</li><li>Adapter: The wrapper object that translates the interface of the Adaptee to the Target interface.</li><li>Adaptee: The existing object with the incompatible interface.</li><li>Client: The object that uses the Adapter to interact with the Adaptee.</li></ul><h3>The Adapter pattern works as follows:</h3><ol><li>The client creates an instance of the Adapter object.</li><li>The client calls a method on the Adapter object.</li><li>The Adapter object translates the call to the appropriate method on the Adaptee object.</li><li>The Adaptee object performs the requested operation.</li><li>The Adapter object translates the result of the operation back to the client.</li></ol><h3>Example 3: 💻</h3><p>Imagine you’re developing an iOS app and you want to use a third-party library. However, the library has a different interface than the interface that your app expects.</p><p>You could try to modify the library’s code to make it compatible with your app, but that’s not always feasible or desirable. You could also try to write your own code to translate between the two interfaces, but that can be time-consuming and error-prone.</p><p>A better solution would be to use an Adapter class. The Adapter class can wrap the third-party library and translate its interface to the interface that your app expects.</p><h3>How to implement the Adapter pattern in iOS?</h3><h4>1- Identify the components involved:</h4><ul><li>Client: The object that will be using the Adapter to interact with the Adaptee.</li><li>Adaptee: The existing class or object that has an incompatible interface with the Client.</li><li>Target: The interface that the Client expects the Adaptee to conform to.</li><li>Adapter: The class or object that bridges the gap between the Client and the Adaptee, implementing the Target interface and delegating the actual work to the Adaptee.</li></ul><h4>2. Create the Target interface:</h4><ul><li>Define a protocol that declares the methods and properties expected by the Client.</li></ul><h4>3. Implement the Adaptee:</h4><ul><li>Create a class or object that provides the actual functionality needed by the Client but has an incompatible interface.</li><li>This could be an existing class or a third-party library that you cannot modify.</li></ul><h4>4. Create the Adapter:</h4><ul><li>Implement the Target interface in a new class or object.</li><li>Add a property to hold a reference to the Adaptee.</li><li>In the Target interface methods, delegate the actual work to the Adaptee.</li></ul><h4>5. Use the Adapter in the Client:</h4><ul><li>Instantiate the Adapter, passing the Adaptee as a parameter.</li><li>Call the methods defined in the Target interface on the Adapter.</li></ul><p>Here’s an example of how to implement the Adapter pattern in iOS using Swift:</p><pre><br>// Step 2: Create the Target interface<br>protocol DataManagerProtocol {<br>    func saveFile()<br>    func readFile()<br>}<br><br>// Step 3: Implement the Adaptee<br>class DataFileManager {<br>    func savePlist() {<br>        print(&quot;The plist file was saved.&quot;)<br>    }<br>    <br>    func readPlist() {<br>        print(&quot;The plist file was read.&quot;)<br>    }<br>}<br><br>// Step 4: Create the Adapter<br>class DataAdapter: DataManagerProtocol {<br>    private var dataFileManager: DataFileManager<br>    <br>    init(dataFileManager: DataFileManager) {<br>        self.dataFileManager = dataFileManager<br>    }<br>    <br>    func saveFile() {<br>        dataFileManager.savePlist()<br>    }<br>    <br>    func readFile() {<br>        dataFileManager.readPlist()<br>    }<br>}<br><br>// Step 5: Use the Adapter in the Client<br>class DataManager {<br>    func saveTheTestFile(forAdapter: DataManagerProtocol) {<br>        forAdapter.saveFile()<br>    }<br>}<br><br>// Usage<br>let dataFileManager = DataFileManager()<br>let dataAdapter = DataAdapter(dataFileManager: dataFileManager)<br>let dataManager = DataManager()<br><br>dataManager.saveTheTestFile(forAdapter: dataAdapter)</pre><blockquote>In this example, we have a DataFileManager class that provides the actual functionality of saving and reading a plist file. However, its interface is incompatible with the DataManager class, which expects an object that conforms to the DataManagerProtocol.To bridge this gap, we create a DataAdapter class that implements the DataManagerProtocol and delegates the actual work to the DataFileManager instance. We then use the DataAdapter instance in the DataManager class to save the test file, without the DataManager class needing to know the details of how the file is actually saved and read.</blockquote><h3>Example 4: 💪</h3><p>Let’s say we are building a task management app that integrates with a third-party API to fetch and display tasks. The API provides a structure called APITask that represents a task with various properties like id, createdAt, createdBy, developedBy, and finishedAt. However, our app uses a different structure called Task to represent tasks, which has similar properties but with different names and types.To solve this problem, we can use the Adapter pattern to adapt the APITask structure to our Task structure. Here&#39;s the code for the adapter:</p><pre>struct Task {<br>    let taskId: String<br>    let creationDate: Date<br>    let creator: String<br>    let developer: String<br>    let completionDate: Date?<br>}<br><br>struct APITask {<br>    let id: String<br>    let createdAt: TimeInterval<br>    let createdBy: String<br>    let developedBy: String<br>    let finishedAt: TimeInterval?<br>}<br><br>protocol TaskAdapter {<br>    func adapt(apiTask: APITask) -&gt; Task<br>}<br><br>struct DefaultTaskAdapter: TaskAdapter {<br>    private let dateFormatter: DateFormatter<br>    <br>    init() {<br>        dateFormatter = DateFormatter()<br>        dateFormatter.dateFormat = &quot;yyyy-MM-dd HH:mm:ss&quot;<br>    }<br>    <br>    func adapt(apiTask: APITask) -&gt; Task {<br>        let creationDate = Date(timeIntervalSince1970: apiTask.createdAt)<br>        let completionDate = apiTask.finishedAt.map { Date(timeIntervalSince1970: $0) }<br>        <br>        return Task(<br>            taskId: apiTask.id,<br>            creationDate: creationDate,<br>            creator: apiTask.createdBy,<br>            developer: apiTask.developedBy,<br>            completionDate: completionDate<br>        )<br>    }<br>}</pre><p>In this example, we have a Task structure that represents a task in our app, and an APITask structure that represents a task in the third-party API. We also have a TaskAdapter protocol that defines a method for adapting an APITask to a Task. The DefaultTaskAdapter struct implements the TaskAdapter protocol and provides a default implementation for adapting an APITask to a Task.To use the adapter, we can fetch tasks from the API and then adapt them to our Task structure:</p><pre>class TaskManager {<br>    private let apiClient: APIClient<br>    private let taskAdapter: TaskAdapter<br>    <br>    init(apiClient: APIClient, taskAdapter: TaskAdapter) {<br>        self.apiClient = apiClient<br>        self.taskAdapter = taskAdapter<br>    }<br>    <br>    func fetchTasks(completion: @escaping (Result&lt;[Task], Error&gt;) -&gt; Void) {<br>        apiClient.fetchAPITasks { result in<br>            switch result {<br>            case .success(let apiTasks):<br>                let tasks = apiTasks.map { self.taskAdapter.adapt(apiTask: $0) }<br>                completion(.success(tasks))<br>            case .failure(let error):<br>                completion(.failure(error))<br>            }<br>        }<br>    }<br>}</pre><p>In this example, we have a TaskManager class that is responsible for fetching tasks from the API. It takes an APIClient and a TaskAdapter as dependencies. When fetchTasks is called, it uses the apiClient to fetch APITasks, and then uses the taskAdapter to adapt them to Tasks.This way, we can fetch tasks from the API and work with them in our app using our Task structure, without having to modify the API or our Task structure to make them compatible.Alternative approach:Instead of using a separate TaskAdapter struct, we can also use a Swift extension to make the APITask structure conform to the Task structure. Here&#39;s the code for the alternative approach:</p><pre>extension APITask {<br>    func adapt() -&gt; Task {<br>        let creationDate = Date(timeIntervalSince1970: self.createdAt)<br>        let completionDate = self.finishedAt.map { Date(timeIntervalSince1970: $0) }<br>        <br>        return Task(<br>            taskId: self.id,<br>            creationDate: creationDate,<br>            creator: self.createdBy,<br>            developer: self.developedBy,<br>            completionDate: completionDate<br>        )<br>    }<br>}</pre><p>With this approach, we can remove the TaskAdapter protocol and the DefaultTaskAdapter struct, and directly call the adapt method on an APITask to get a Task. However, this approach may not be suitable in all cases, especially when we need to adapt multiple types to a common interface.</p><h3>Example 5: 🐉</h3><p>Let’s say we have an existing iOS app that uses a custom Image class to display images from a local or remote source. However, we want to integrate a third-party image loading library called SDWebImage into our app, which has a different interface for loading and caching images. We can use the Adapter pattern to make the SDWebImage library work with our existing Image class without modifying it.</p><h4>Solution</h4><ol><li>First, we define our existing Image class, which has a simple interface for loading and displaying images:</li></ol><pre>class Image {<br>    private let imageView: UIImageView<br>    <br>    init(imageView: UIImageView) {<br>        self.imageView = imageView<br>    }<br>    <br>    func load(from url: URL) {<br>        // Load image from URL and set it on the image view<br>    }<br>}</pre><p>2. Next, we create an adapter class called SDWebImageAdapter that conforms to the interface of our Image class but uses the SDWebImage library to load and cache images:</p><pre>import SDWebImage<br><br>class SDWebImageAdapter: Image {<br>    private let imageView: UIImageView<br>    <br>    init(imageView: UIImageView) {<br>        self.imageView = imageView<br>    }<br>    <br>    override func load(from url: URL) {<br>        imageView.sd_setImage(with: url)<br>    }<br>}</pre><p>3. Now, we can use the SDWebImageAdapter class in our app to load and display images using the SDWebImage library, without modifying our existing Image class:</p><pre>let imageView = UIImageView()<br>let image = SDWebImageAdapter(imageView: imageView)<br>image.load(from: imageURL)</pre><p>In this example, the SDWebImageAdapter class acts as a wrapper between our Image class and the SDWebImage library, allowing them to collaborate and load images from a remote source. The adapter class translates the load(from:) method call into a format and interface recognizable by the SDWebImage library, enabling it to load and cache the image</p><h3>Advantages of the Adapter pattern in iOS:</h3><ul><li>Seamless integration of third-party code: The Adapter pattern allows you to use code from third-party libraries or APIs without changing your existing interfaces .This can be especially useful when working with legacy code or when you can’t modify the implementation of a third-party library.</li><li>Improved reusability and flexibility: By using adapters, you can achieve better code reusability and flexibility. The client class is not complicated by having to use a different interface and can use polymorphism to swap between different implementations of adapters</li><li>Separation of concerns: The Adapter pattern helps separate the interface code from the main business logic code, following the single responsibility principle.This can lead to cleaner and more maintainable code.</li></ul><h3>Disadvantages of Adapter pattern in iOS:</h3><ul><li>Increased complexity and overhead: One of the main drawbacks of the Adapter pattern is that it introduces additional complexity and overhead to your code. The adapter class acts as an intermediary between the two interfaces, which means it has to perform extra operations to convert the data, handle exceptions, and delegate calls. This can increase memory usage, execution time, and maintenance costs.</li><li>Coupling and dependency between interfaces: The Adapter pattern creates coupling and dependency between the original interface, the adapted interface, and the adapter class. Any changes in either of the interfaces can affect the adapter class and the rest of the code that uses it. For example, if the original interface adds a new method or modifies an existing one, the adapter class may need to be updated or extended to reflect the change.</li></ul><h3>Tips for using Adapter design pattern in iOS:</h3><h4>1- Identify the client, target interface, and adaptee:</h4><ul><li>The client is the object that will use the adapter.</li><li>The target interface is the interface that the client expects.</li><li>The adaptee is the object with an incompatible interface that needs to be adapted to the target interface.</li></ul><h4>2- Create an adapter:</h4><ul><li>The adapter can be implemented as a class or struct that conforms to the target interface and wraps the adaptee object.</li><li>Alternatively, you can use Swift extensions to extend the adaptee and make it conform to the target interface</li></ul><h4>3- Implement the necessary methods and properties in the adapter:</h4><ul><li>The adapter should provide implementations for the methods and properties defined in the target interface, using the adaptee object to perform the required functionality.</li></ul><h4>4- Use the adapter in the client code:</h4><ul><li>Instead of directly using the adaptee object, the client should use the adapter object, which provides the adapted interface.</li></ul><h3>Finally:</h3><p>The Adapter design pattern is a powerful tool that can be used to make your iOS code more modular, reusable, maintainable, and extensible. Use it judiciously and document your adapters clearly.</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e008ec29414" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/adapter-design-pattern-in-ios-9e008ec29414">Adapter Design Pattern in iOS</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain Of Responsibility Design Pattern in iOS]]></title>
            <link>https://blog.stackademic.com/chain-of-responsibility-design-pattern-in-ios-2b567f7240ad?source=rss-aad284ffbae6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b567f7240ad</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Omar Saibaa]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 16:16:57 GMT</pubDate>
            <atom:updated>2023-11-06T16:16:57.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cb2h9Ut1Gw-3RNVb" /></figure><p>The Chain of Responsibility design pattern is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.</p><p>The chain of responsibility pattern is often used in situations where there is a chain of command, such as in a military or corporate setting. It can also be used in situations where there are multiple ways to handle a request, such as in a web application where different components can handle different types of requests.</p><h3>The chain of responsibility pattern consists of the following components:</h3><ul><li>Subject: The subject is the object that initiates the request.</li><li>Handler: The handler is an object that can process the request.</li><li>Chain of handlers: The chain of handlers is a linked list of handlers.</li><li>Request: The request is an object that contains the information that the subject needs to be processed.</li></ul><h3>The chain of responsibility pattern works as follows:</h3><ol><li>The subject sends a request to the first handler in the chain.</li><li>The first handler decides either to process the request or to pass it to the next handler in the chain.</li><li>If the first handler processes the request, the request is complete.</li><li>If the first handler passes the request to the next handler in the chain, the process repeats itself.</li></ol><p>The request is processed until it reaches a handler that can process it or until it reaches the end of the chain.</p><h3>Example 1: 👶</h3><p>Imagine a web application that allows users to submit articles. When a user submits an article, the application needs to validate the article before it is published.</p><p>The application could use the chain of responsibility pattern to implement the article validation process. The chain could consist of the following handlers:</p><ul><li>Content handler: This handler checks the content of the article for profanity and other inappropriate content.</li><li>Grammar handler: This handler checks the grammar and spelling of the article.</li><li>Plagiarism handler: This handler checks the article for plagiarism.</li></ul><p>If any of the handlers find a problem with the article, they can reject the article and return an error message to the user. Otherwise, the article is published.</p><h3>Example 2: 🍎</h3><p>Scrum is an agile framework for developing products and services. Scrum teams typically consist of a Product Owner, Scrum Master, and Development Team.</p><p>The Scrum process can be explained by the chain of responsibility pattern as follows:</p><ul><li>The Product Owner is the first handler in the chain. They are responsible for the vision and success of the product and have the final say on what features are built and how they are prioritized.</li><li>The Scrum Master is the second handler in the chain. They are responsible for ensuring that the Scrum team is following the Scrum process and that they are removing any impediments that are preventing the team from making progress.</li><li>The Development Team is the third handler in the chain. They are responsible for building the product and ensuring that it meets the requirements of the Product Owner.</li></ul><p>When a new feature request is submitted, it is first passed to the Product Owner. The Product Owner decides whether to accept or reject the feature request. If the Product Owner accepts the feature request, they prioritize it and add it to the Product Backlog.</p><p>The Product Owner then works with the Scrum Master to help the Development Team to break down the feature request into smaller tasks and to create a Sprint Backlog. The Development Team then works on the Sprint Backlog items during the Sprint.</p><p>If the Development Team encounters any impediments during the Sprint, they escalate the impediment to the Scrum Master. The Scrum Master then works to remove the impediment so that the Development Team can continue working on the Sprint Backlog items.</p><p>Once the Development Team has completed all of the Sprint Backlog items, they present the completed work to the Product Owner and the Scrum Master during the Sprint Review. The Product Owner then decides whether to accept or reject the completed work. If the Product Owner accepts the completed work, it is added to the Increment.</p><p>The Scrum Master then facilitates a Sprint Retrospective meeting, where the Development Team, the Product Owner, and the Scrum Master reflect on the Sprint and identify areas for improvement.</p><p>The chain of responsibility pattern is a powerful design pattern that can be used to implement a variety of different systems. It is a flexible and reusable pattern that can help to make your code more modular and maintainable.</p><p>Let’s take an example of how to deal with a single feature step-by-step :</p><ul><li>A new feature request is submitted to the Product Owner.</li><li>The Product Owner reviews the feature request and decides to accept it.</li><li>The Product Owner prioritizes the feature request and adds it to the Product Backlog.</li><li>During the Sprint Planning meeting, the Scrum Master and Development Team work together to select the feature request from the Product Backlog and to break it down into smaller tasks.</li><li>The Development Team adds the tasks to the Sprint Backlog and begins working on them.</li><li>During the Sprint, the Development Team encounters an impediment. They escalate the impediment to the Scrum Master.</li><li>The Scrum Master works to remove the impediment so that the Development Team can continue working on the Sprint Backlog items.</li><li>At the end of the Sprint, the Development Team presents the completed work to the Product Owner and the Scrum Master during the Sprint Review.</li><li>The Product Owner accepts the completed work.</li><li>The Scrum Master facilitates a Sprint Retrospective meeting, where the Development Team, the Product Owner, and the Scrum Master reflect on the Sprint and identify areas for improvement.</li></ul><p>In this example, the Product Owner, Scrum Master, and Development Team are all handlers in the chain of responsibility. The feature request is passed from the Product Owner to the Scrum Master to the Development Team. Each handler decides whether to process the request or to pass it to the next handler in the chain.</p><h3>Example 3: 💻</h3><p>Imagine a restaurant with a chain of responsibility for taking and fulfilling food orders.</p><ul><li>Subject: The customer is the subject. They initiate the request by ordering food.</li><li>Handler: The waiter is the handler. They receive the request from the customer and decide whether to process it themselves or pass it to the next handler in the chain.</li><li>Chain of handlers: The chain of handlers is the kitchen staff. The waiter passes the request to the kitchen staff, who are responsible for preparing the food.</li><li>Request: The request is the food order.</li></ul><h4>The chain of responsibility pattern work as follow:</h4><p>1. The subject sends a request to the first handler in the chain.<br>In the restaurant example, the customer sends their food order to the waiter.</p><p>2. The first handler decides either to process the request or to pass it to the next handler in the chain.<br>The waiter can either take the food order directly to the kitchen or pass it to another waiter.</p><p>3. If the first handler processes the request, the request is complete.<br>If the waiter takes the food order directly to the kitchen, the request is complete.</p><p>4. If the first handler passes the request to the next handler in the chain, the process repeats itself.<br>If the waiter passes the food order to another waiter, the process repeats itself until the food order reaches the kitchen staff.</p><h3>How to implement the chain of responsibility pattern in iOS?</h3><ol><li>Create a protocol for the handlers. This protocol should define a method for handling requests.</li><li>Create concrete handler classes that implement the protocol. Each handler should be responsible for handling a specific type of request.</li><li>Create a chain of handlers. This can be done by linking the handlers together in a linked list or using a tree structure.</li><li>Pass the request to the first handler in the chain. The handler will then decide whether to process the request itself or pass it to the next handler in the chain.</li><li>Continue passing the request to the next handler in the chain until it is processed or the end of the chain is reached.</li></ol><p>Here is a simple example of how to implement the Chain of Responsibility pattern in iOS:</p><pre>protocol RequestHandler {<br>    func handle(request: Request) -&gt; Bool<br>}<br><br>class Request {<br>    var type: String<br>    var data: Any<br><br>    init(type: String, data: Any) {<br>        self.type = type<br>        self.data = data<br>    }<br>}<br><br>class ConcreteRequestHandler1: RequestHandler {<br>    func handle(request: Request) -&gt; Bool {<br>        if request.type == &quot;my-type-1&quot; {<br>            // Process the request.<br>            return true<br>        } else {<br>            return false<br>        }<br>    }<br>}<br><br>class ConcreteRequestHandler2: RequestHandler {<br>    func handle(request: Request) -&gt; Bool {<br>        if request.type == &quot;my-type-2&quot; {<br>            // Process the request.<br>            return true<br>        } else {<br>            return false<br>        }<br>    }<br>}<br><br>class ChainOfResponsibility {<br>    private var firstHandler: RequestHandler?<br><br>    func addHandler(handler: RequestHandler) {<br>        if firstHandler == nil {<br>            firstHandler = handler<br>        } else {<br>            var currentHandler = firstHandler<br>            while currentHandler?.nextHandler != nil {<br>                currentHandler = currentHandler?.nextHandler<br>            }<br>            currentHandler?.nextHandler = handler<br>        }<br>    }<br><br>    func handle(request: Request) -&gt; Bool {<br>        return firstHandler?.handle(request: request) ?? false<br>    }<br>}</pre><p>To use the ChainOfResponsibility class, you would first create a chain of handlers. You can do this by adding handlers to the chain using the addHandler() method.</p><p>Once you have created a chain of handlers, you can pass requests to the chain using the handle() method. The chain will then pass the request to the first handler in the chain. The handler will then decide whether to process the request itself or pass it to the next handler in the chain.</p><p>This process will continue until the request is processed or the end of the chain is reached.</p><p>Here is an example of how to use the ChainOfResponsibility class:</p><pre>let chainOfResponsibility = ChainOfResponsibility()<br><br>// Add handlers to the chain.<br>chainOfResponsibility.addHandler(handler: ConcreteRequestHandler1())<br>chainOfResponsibility.addHandler(handler: ConcreteRequestHandler2())<br><br>// Pass a request to the chain.<br>let request = Request(type: &quot;my-type-1&quot;, data: &quot;some-data&quot;)<br><br>// The chain will process the request.<br>let response = chainOfResponsibility.handle(request: request)<br><br>if response {<br>    // The request was processed successfully.<br>} else {<br>    // The request was not processed successfully.<br>}</pre><h3>Example 4: 💪</h3><p>In a typical iOS app, there are many different types of events that can occur, such as user interface events, network events, and sensor events. It can be difficult and cumbersome to handle all of these events directly in the app’s main codebase.</p><p>The Chain of Responsibility design pattern provides a way to handle events in a loose-coupled and scalable manner. The pattern works by defining a chain of handlers, each of which is responsible for handling a specific type of event. When an event occurs, the app passes the event to the first handler in the chain. The handler then decides whether to handle the event itself or to pass it to the next handler in the chain. This process continues until the event is handled by one of the handlers in the chain.</p><p>The next code shows how to use the Chain of Responsibility design pattern to handle user interface events in an iOS app:</p><pre>// Define the different types of user interface events that can occur.<br>enum UserInterfaceEvent {<br>    case buttonTapped<br>    case textFieldChanged<br>    case tableViewCellSelected<br>}<br><br>// Define a protocol for the handlers that will handle the user interface events.<br>protocol UserInterfaceEventHandler {<br>    func handleEvent(event: UserInterfaceEvent)<br>}<br><br>// Define a concrete handler for each type of user interface event.<br>class ButtonTappedHandler: UserInterfaceEventHandler {<br>    func handleEvent(event: UserInterfaceEvent) {<br>        if event == .buttonTapped {<br>            // Handle the button tapped event.<br>        }<br>    }<br>}<br><br>class TextFieldChangedHandler: UserInterfaceEventHandler {<br>    func handleEvent(event: UserInterfaceEvent) {<br>        if event == .textFieldChanged {<br>            // Handle the text field changed event.<br>        }<br>    }<br>}<br><br>class TableViewCellSelectedHandler: UserInterfaceEventHandler {<br>    func handleEvent(event: UserInterfaceEvent) {<br>        if event == .tableViewCellSelected {<br>            // Handle the table view cell selected event.<br>        }<br>    }<br>}<br><br>// Define a chain of responsibility for the user interface events.<br>class UserInterfaceEventChainOfResponsibility {<br>    private var handlers = [UserInterfaceEventHandler]()<br><br>    func registerHandler(handler: UserInterfaceEventHandler) {<br>        handlers.append(handler)<br>    }<br><br>    func handleEvent(event: UserInterfaceEvent) {<br>        for handler in handlers {<br>            handler.handleEvent(event: event)<br>            // Break the chain if the event has been handled.<br>            if event.isHandled {<br>                break<br>            }<br>        }<br>    }<br>}<br><br>// Usage<br><br>// Create a user interface event chain of responsibility.<br>let userInterfaceEventChainOfResponsibility = UserInterfaceEventChainOfResponsibility()<br><br>// Register the handlers for the different types of user interface events.<br>userInterfaceEventChainOfResponsibility.registerHandler(handler: ButtonTappedHandler())<br>userInterfaceEventChainOfResponsibility.registerHandler(handler: TextFieldChangedHandler())<br>userInterfaceEventChainOfResponsibility.registerHandler(handler: TableViewCellSelectedHandler())<br><br>// Handle a user interface event.<br>let event = UserInterfaceEvent.buttonTapped<br><br>// Pass the event to the user interface event chain of responsibility.<br>userInterfaceEventChainOfResponsibility.handleEvent(event: event)</pre><h3>Example 5: 🐉</h3><p>The Twitter app needs to handle a variety of different events, such as the user tapping on a tweet, the user liking a tweet, or the user retweeting a tweet. The Twitter app does not want to have to keep track of all of these events and handle them directly. This would be inefficient and would not scale well.</p><p>The Twitter app uses the Chain of Responsibility pattern to solve this problem. The app has a series of handlers, each of which is responsible for handling a different type of event. When an event occurs, the app passes the event to the first handler in the chain. The handler then decides whether to handle the event itself or to pass it to the next handler in the chain. This process continues until the event is handled by one of the handlers in the chain.</p><p>Code:</p><pre>protocol TwitterEventHandler {<br>    func handleEvent(event: TwitterEvent)<br>}<br><br>class TwitterTweetTappedHandler: TwitterEventHandler {<br>    func handleEvent(event: TwitterEvent) {<br>        if event is TweetTappedEvent {<br>            // Handle the tweet tapped event.<br>        }<br>    }<br>}<br><br>class TwitterLikeTweetHandler: TwitterEventHandler {<br>    func handleEvent(event: TwitterEvent) {<br>        if event is LikeTweetEvent {<br>            // Handle the like tweet event.<br>        }<br>    }<br>}<br><br>class TwitterRetweetTweetHandler: TwitterEventHandler {<br>    func handleEvent(event: TwitterEvent) {<br>        if event is RetweetTweetEvent {<br>            // Handle the retweet tweet event.<br>        }<br>    }<br>}<br><br>class TwitterEventChainOfResponsibility {<br>    private var handlers = [TwitterEventHandler]()<br><br>    func registerHandler(handler: TwitterEventHandler) {<br>        handlers.append(handler)<br>    }<br><br>    func handleEvent(event: TwitterEvent) {<br>        for handler in handlers {<br>            handler.handleEvent(event: event)<br>            // Break the chain if the event has been handled.<br>            if event.isHandled {<br>                break<br>            }<br>        }<br>    }<br>}<br><br>// Usage<br><br>let eventChainOfResponsibility = TwitterEventChainOfResponsibility()<br><br>// Register handlers.<br>eventChainOfResponsibility.registerHandler(handler: TwitterTweetTappedHandler())<br>eventChainOfResponsibility.registerHandler(handler: TwitterLikeTweetHandler())<br>eventChainOfResponsibility.registerHandler(handler: TwitterRetweetTweetHandler())<br><br>// Handle an event.<br>let event = TweetTappedEvent()<br>eventChainOfResponsibility.handleEvent(event: event)</pre><h3>Advantages of Chain of Responsibility pattern in iOS:</h3><ul><li>Loose coupling: The Chain of Responsibility pattern promotes loose coupling between objects. This means that objects are loosely coupled when they have minimal knowledge about each other’s internal implementation. This makes the system more flexible and scalable.</li><li>Reusability: The Chain of Responsibility pattern is reusable because it can be used in a variety of different situations. For example, the Chain of Responsibility pattern can be used to implement a user interface event handling system, a data validation system, or a security system.</li><li>Scalability: The Chain of Responsibility pattern is scalable because it can handle any number of handlers. This makes it ideal for systems that need to be able to handle a large number of requests.</li><li>Performance: The Chain of Responsibility pattern can improve performance by avoiding the need for conditional statements to determine which object is responsible for handling a request. Instead, the request is simply passed to the first handler in the chain, and the chain handles the rest.</li></ul><h3>Disadvantages of Chain of Responsibility pattern in iOS:</h3><ul><li>Complexity: The Chain of Responsibility pattern can become complex if there are a large number of handlers in the chain. This can make it difficult to understand and maintain the system.</li><li>Order dependency: The Chain of Responsibility pattern can be order-dependent, meaning that the order in which the handlers are linked together can affect the way that requests are processed. This can make it difficult to debug the system if there are problems with the order of the handlers.</li><li>Performance overhead: The Chain of Responsibility pattern can add some performance overhead, because each handler in the chain needs to check whether it is responsible for handling the request before passing it to the next handler.</li></ul><h3>Tips for using Chain of Responsibility pattern in iOS:</h3><ul><li>Use the pattern when there is a clear chain of responsibility:<br>This means that there is a natural order in which requests should be processed. For example, a user interface event handling system would have a clear chain of responsibility, with the event first being handled by the view that received the event, and then being passed up the view hierarchy until it is handled by a view that is responsible for handling the event.</li><li>Avoid using the pattern if there are a large number of handlers in the chain:<br>This is because the Chain of Responsibility pattern can become complex and difficult to maintain if there are a large number of handlers. If there are a large number of handlers, it may be better to use a different design pattern, such as the Mediator pattern.</li><li>Carefully consider the order in which the handlers are linked together:<br>The order in which the handlers are linked together can affect the way that requests are processed. For example, if a view hierarchy has a button and a text field, and the button is linked before the text field in the Chain of Responsibility, then the button will be responsible for handling all events before the text field has a chance to handle them.</li><li>Test the system thoroughly to ensure that requests are being processed correctly:<br>The Chain of Responsibility pattern can be difficult to debug, so it is important to test the system thoroughly to ensure that requests are being processed correctly.</li></ul><h3>Finally:</h3><p>The Chain of Responsibility design pattern is a powerful design pattern that can be used to implement a variety of different systems in iOS. It is a flexible and reusable pattern, but it can become complex if there are a large number of handlers in the chain. It is important to carefully consider the order in which the handlers are linked together and to test the system thoroughly to ensure that requests are being processed correctly.</p><h3>Thanks for reading and Don’t forget to claps, comment and follow me for more.</h3><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b567f7240ad" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/chain-of-responsibility-design-pattern-in-ios-2b567f7240ad">Chain Of Responsibility Design Pattern in iOS</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>