<?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 Mehrdad Ahmadian on Medium]]></title>
        <description><![CDATA[Stories by Mehrdad Ahmadian on Medium]]></description>
        <link>https://medium.com/@mehrdad-ahmadian?source=rss-f8fe1c4a605d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t8Y9JIiHaQWU3Sm5Hqg3cw.png</url>
            <title>Stories by Mehrdad Ahmadian on Medium</title>
            <link>https://medium.com/@mehrdad-ahmadian?source=rss-f8fe1c4a605d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:04:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehrdad-ahmadian/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[iOS Interview Question: Building a Custom Set Data Structure Using TDD in Swift]]></title>
            <link>https://mehrdad-ahmadian.medium.com/ios-interview-question-building-a-custom-set-data-structure-using-tdd-in-swift-d67e7a9e023f?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d67e7a9e023f</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 15:08:48 GMT</pubDate>
            <atom:updated>2024-07-12T06:33:41.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcohRqnFAF2KJQkNW0K3bQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@3tnik?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Ave Calvar</a> on <a href="https://unsplash.com/photos/blue-red-and-yellow-color-pencils-nKF2QcKsYx4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>Recently, during an interview for an iOS Developer role, I was asked to implement a Set data structure in Swift using Test-Driven Development (TDD). The task involved creating a custom Set that supports methods like isEmpty, add, contains, remove, and resizing when necessary. The interviewers emphasized following the TDD process: writing tests first, failing them, implementing the functionality, and finally passing the tests.</p><p>In this tutorial, I will walk you through how I approached this task using TDD, providing a detailed step-by-step guide on building a robust Set data structure in Swift.</p><p><strong>Step 1: Setting Up the Project</strong></p><p>Create a new Swift project in Xcode and set up the test target. We’ll be using the XCTest framework for writing and running our tests.</p><p><strong>Step 2: Writing the Tests and Implementing the Methods</strong></p><p><strong>Test 1: isEmpty</strong></p><p>First, we’ll write the method signature in the Set class, then a test to check if the set is empty.</p><pre>import XCTest<br><br>@testable import SetDataStructure<br><br>final class SetDataStructureTests: XCTestCase {<br><br>    func testIsEmpty() {<br>        let set = Set&lt;Int&gt;()<br>        XCTAssertTrue(set.isEmpty)<br>        set.add(1)<br>        XCTAssertFalse(set.isEmpty)<br>    }<br>}</pre><p>Run the test. It should fail because we haven’t implemented the method in the Set class yet.</p><p><strong>Implementation 1: isEmpty</strong></p><p>We’ll start by implementing the isEmpty method.</p><pre>class Set&lt;T: Hashable&gt; {<br>    private var elements: [T: Bool]<br>    private(set) var count: Int<br>    <br>    init(initialCapacity: Int = 10) {<br>        self.elements = [T: Bool](minimumCapacity: initialCapacity)<br>        self.count = 0<br>    }<br>    <br>    var isEmpty: Bool {<br>        count == 0<br>    }<br>}</pre><p>Run the test for isEmpty. It should pass now.</p><p><strong>Test 2: add</strong></p><p>Next, we’ll write a test to add elements to the set.</p><pre>func testAdd() {<br>    let set = Set&lt;Int&gt;()<br>    XCTAssertTrue(set.isEmpty)<br>    set.add(1)<br>    XCTAssertEqual(set.count, 1)<br>    set.add(1)  // Trying to add a duplicate<br>    XCTAssertEqual(set.count, 1)  // Count should not change<br>}</pre><p>Run the test. It should fail because we don’t have an implementation yet.</p><p><strong>Implementation 2: add</strong></p><p>Next, we’ll implement the add method.</p><pre>func add(_ element: T) {<br>    if elements[element] == nil {<br>        elements[element] = true<br>        count += 1<br>    }<br>}</pre><p>Run the test for add. It should pass now.</p><p><strong>Test 3: contains</strong></p><p>We’ll now write a test to check if the set contains a specific element.</p><pre>func testContains() {<br>    let set = Set&lt;Int&gt;()<br>    XCTAssertFalse(set.contains(1))<br>    set.add(1)<br>    XCTAssertTrue(set.contains(1))<br>}</pre><p>Run the test. It should fail.</p><p><strong>Implementation 3: contains</strong></p><p>Now, we’ll implement the contains method.</p><pre>func contains(_ element: T) -&gt; Bool {<br>    return elements[element] != nil<br>}</pre><p>Run the test for contains. It should pass now.</p><p><strong>Test 4: remove</strong></p><p>Let’s write a test to remove elements from the set.</p><pre>func testRemove() {<br>    let set = Set&lt;Int&gt;()<br>    set.add(1)<br>    set.add(2)<br>    set.add(3)<br>    XCTAssertTrue(set.contains(2))<br>    set.remove(2)<br>    XCTAssertFalse(set.contains(2))<br>    XCTAssertTrue(set.contains(3))<br>}</pre><p>Run the test. It should fail.</p><p><strong>Implementation 4: remove</strong></p><p>Next, we’ll implement the remove method.</p><pre>func remove(_ element: T) {<br>    if elements[element] != nil {<br>        elements[element] = nil<br>        count -= 1<br>    }<br>}</pre><p>Run the test for remove. It should pass now.</p><p><strong>Test 5: resize</strong></p><p>Finally, we’ll write a test to check if the set resizes correctly when the initial capacity is exceeded.</p><pre>func testResize() {<br>    let set = Set&lt;Int&gt;(initialCapacity: 2)<br>    set.add(1)<br>    set.add(2)<br>    XCTAssertEqual(set.count, 2)<br>    set.add(3)<br>    XCTAssertEqual(set.count, 3)<br>}</pre><p>Run the test, it should pass. Note that resizing a hash table is typically handled by the dictionary itself, so it’s mostly abstracted away.</p><p><strong>Conclusion</strong></p><p>We have successfully built a custom Set data structure using TDD. By writing tests first and then implementing the functionality, we ensure that our code is robust and behaves as expected. This approach can be applied to other data structures and algorithms to improve code quality and reliability.</p><p><strong>Full Code</strong></p><p>Here’s the complete code for the Set class and the test cases:</p><p><strong>Set.swift</strong></p><pre>import Foundation<br><br>// Elements in Set are unordered and unique<br><br>class Set&lt;T: Hashable&gt; {<br>    private var elements: [T: Bool]<br>    private(set) var count: Int<br>    <br>    init(initialCapacity: Int = 10) {<br>        self.elements = [T: Bool](minimumCapacity: initialCapacity)<br>        self.count = 0<br>    }<br>    <br>    var isEmpty: Bool {<br>        count == 0<br>    }<br>    <br>    func add(_ element: T) {<br>        if elements[element] == nil {<br>            elements[element] = true<br>            count += 1<br>        }<br>    }<br>    <br>    func contains(_ element: T) -&gt; Bool {<br>        return elements[element] != nil<br>    }<br>    <br>    func remove(_ element: T) {<br>        if elements[element] != nil {<br>            elements[element] = nil<br>            count -= 1<br>        }<br>    }<br>}</pre><p><strong>SetDataStructureTests.swift</strong></p><pre>import XCTest<br>@testable import YourProjectName<br><br>final class SetDataStructureTests: XCTestCase {<br><br>    func testIsEmpty() {<br>        let set = Set&lt;Int&gt;()<br>        XCTAssertTrue(set.isEmpty)<br>        set.add(1)<br>        XCTAssertFalse(set.isEmpty)<br>    }<br>    <br>    func testAdd() {<br>        let set = Set&lt;Int&gt;()<br>        XCTAssertTrue(set.isEmpty)<br>        set.add(1)<br>        XCTAssertEqual(set.count, 1)<br>        set.add(1) // Trying to add duplicate<br>        XCTAssertEqual(set.count, 1) // Count should not change<br>    }<br>    <br>    func testContains() {<br>        let set = Set&lt;Int&gt;()<br>        XCTAssertFalse(set.contains(1))<br>        set.add(1)<br>        XCTAssertTrue(set.contains(1))<br>    }<br>    <br>    func testRemove() {<br>        let set = Set&lt;Int&gt;()<br>        set.add(1)<br>        set.add(2)<br>        set.add(3)<br>        XCTAssertTrue(set.contains(2))<br>        set.remove(2)<br>        XCTAssertFalse(set.contains(2))<br>        XCTAssertTrue(set.contains(3))<br>    }<br>    <br>    func testResize() {<br>        let set = Set&lt;Int&gt;(initialCapacity: 2)<br>        set.add(1)<br>        set.add(2)<br>        XCTAssertEqual(set.count, 2)<br>        set.add(3)<br>        XCTAssertEqual(set.count, 3)<br>    }<br>}</pre><p>This concludes our TDD tutorial for building a custom Set data structure in Swift.</p><p>This structure ensures clarity by demonstrating each step of the TDD process — writing a test, failing it, writing the implementation, passing the test, and moving on to the next method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d67e7a9e023f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS FAANG Interview Question 2: Converting a Binary Search Tree to a Circular Doubly Linked List in…]]></title>
            <link>https://mehrdad-ahmadian.medium.com/ios-faang-interview-question-2-converting-a-binary-search-tree-to-a-circular-doubly-linked-list-in-351fcf83c408?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/351fcf83c408</guid>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Wed, 29 May 2024 20:54:15 GMT</pubDate>
            <atom:updated>2024-05-29T20:54:15.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS FAANG Interview Question 2: Converting a Binary Search Tree to a Circular Doubly Linked List in Place</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hA3z7wY2ZgqaXQWcv78lsQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alesnesetril?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Ales Nesetril</a> on <a href="https://unsplash.com/photos/gray-and-black-laptop-computer-on-surface-Im7lZjxeLhg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>I recently had an interview with one of the FAANG companies and faced an intriguing problem: transforming a Binary Search Tree (BST) into a circular doubly linked list in place. This exercise tests your understanding of tree traversal, linked list manipulation, and in-place transformations. Below, we’ll walk through how to achieve this transformation and return a pointer to the smallest element of the linked list.</p><h3>Problem Statement</h3><p>Given a binary search tree, convert it into a circular doubly linked list in place. Each node in the linked list should follow the in-order traversal order of the BST. The left and right pointers in the tree should be used as the previous and next pointers in the linked list. Finally, return a pointer to the smallest element of the linked list.</p><h3>Example</h3><h4>Input:</h4><pre>      4<br>     / \<br>    2   5<br>   / \<br>  1   3</pre><h4>Output:</h4><pre>Circular Doubly Linked List: 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 1 (circular)</pre><h3>Approach</h3><p>To solve this problem, we’ll use a depth-first search (DFS) traversal to visit each node in an in-order sequence. We’ll maintain pointers to the first and last nodes visited to link the nodes correctly. After the traversal, we’ll link the first and last nodes to form a circular doubly linked list.</p><h3>Detailed Solution</h3><p>Here’s the Swift implementation of the solution. First, let’s take a look at the <strong><em>TreeNode</em></strong> implementation:</p><pre>class TreeNode {<br>    var val: Int<br>    var left: TreeNode?<br>    var right: TreeNode?<br>    <br>    init(_ val: Int) {<br>        self.val = val<br>        self.left = nil<br>        self.right = nil<br>    }<br>}</pre><p>Now the solution, using DFS traversal:</p><pre>class Solution {<br>    private var first: TreeNode? = nil<br>    private var last: TreeNode? = nil<br>    <br>    func treeToDoublyList(_ root: TreeNode?) -&gt; TreeNode? {<br>        guard let root else { return nil }<br>        <br>        dfs(root)<br>        <br>        // Close the circular doubly linked list<br>        first?.left = last<br>        last?.right = first<br>        <br>        return first<br>    }<br>        <br>    private func dfs(_ node: TreeNode?) {<br>        guard let node else { return }<br>        <br>        dfs(node.left)<br>        <br>        if last != nil {<br>            // Link the previous node (last) with the current one (node)<br>            last?.right = node<br>            node.left = last<br>        } else {<br>            // If this is the first node, mark it as &#39;first&#39;<br>            first = node<br>        }<br>        <br>        // Mark the current node as &#39;last&#39;<br>        last = node<br>        <br>        dfs(node.right)<br>    }<br>}</pre><p>Lastly, we’ll use a helper method to print the nodes and see a test case:</p><pre>// Helper function to print the circular doubly linked list<br>func printList(_ head: TreeNode?) {<br>    var node = head<br>    var result: [Int] = []<br>    repeat {<br>        if let currentNode = node {<br>            result.append(currentNode.val)<br>            node = currentNode.right<br>        }<br>    } while node !== head<br>    print(result)<br>}<br><br>// Test Case<br>let root = TreeNode(4)<br>root.left = TreeNode(2)<br>root.right = TreeNode(5)<br>root.left?.left = TreeNode(1)<br>root.left?.right = TreeNode(3)<br><br>let solution = Solution()<br>if let head = solution.treeToDoublyList(root) {<br>    printList(head) // Output should be the in-order traversal of the tree: [1, 2, 3, 4, 5]</pre><h3>Explanation</h3><ol><li><strong>TreeNode Class</strong>: This class defines a node in the BST with an integer value, and left and right child pointers.</li><li><strong>Solution Class</strong>:</li></ol><ul><li><strong>Properties</strong>: first and last keep track of the first and last nodes visited during the DFS traversal.</li><li><strong>treeToDoublyList Method</strong>: Initiates the DFS traversal and closes the circular doubly linked list by linking the first and last nodes. Returns the first node, which is the smallest element.</li><li><strong>dfs Method</strong>: Performs an in-order traversal of the tree. During the traversal, it links the current node to the previous node (last) and updates the last pointer.</li></ul><p>3. <strong>printList Function</strong>: A helper function to print the circular doubly linked list, demonstrating that the transformation is correct.</p><h3>Complexity Analysis</h3><ul><li><strong>Time Complexity</strong>: The time complexity of this solution is <strong><em>O(n)</em></strong>, where <strong><em>n</em></strong> is the number of nodes in the BST. This is because each node is visited exactly once during the in-order traversal.</li><li><strong>Space Complexity</strong>: The space complexity is <strong><em>O(m)</em></strong>, where <strong><em>m</em></strong> is the height of the tree. This is the space required for the function call stack during the depth-first search traversal. In the worst case, <strong><em>m</em></strong> can be <strong><em>n</em></strong> for a skewed tree, but for a balanced tree, <strong><em>m</em></strong> would be <strong><em>O(log⁡ n)</em></strong>.</li></ul><h3>Conclusion</h3><p>This approach efficiently converts a BST into a circular doubly linked list in place. Understanding this transformation can be a valuable asset during FAANG interviews, demonstrating your ability to manipulate data structures and perform in-place modifications.</p><p>For a similar problem, you can refer to <a href="https://leetcode.com/problems/convert-binary-search-tree-to-sorted-doubly-linked-list/description/">LeetCode: Convert Binary Search Tree to Sorted Doubly Linked List</a>.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=351fcf83c408" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview Question: Lazy Variables vs Computed Properties in Swift]]></title>
            <link>https://mehrdad-ahmadian.medium.com/ios-interview-question-lazy-variables-vs-computed-properties-in-swift-b35fd323cbbd?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35fd323cbbd</guid>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 04:06:49 GMT</pubDate>
            <atom:updated>2024-01-18T04:08:15.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isJtmqZV4_BTKkBFHCjtXw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nickmorrison?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Nick Morrison</a> on <a href="https://unsplash.com/photos/macbook-pro-near-white-open-book-FHnnjk1Yj7Y?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Among Swift’s rich features that make code more efficient, readable and maintainable, are lazy variables (lazy var) and computed properties, each serving unique roles in programming. Understanding the differences and appropriate use cases for these properties can significantly enhance your coding practices in Swift.</p><h3>What are Lazy Variables (lazy var)?</h3><p>A lazy variable is a property whose initial value is not calculated until the first time it is accessed. This feature is particularly useful for properties that require complex or computationally expensive setup.</p><h3>Key Characteristics of Lazy Variables</h3><ol><li>Deferred Initialization: They are initialized only once, and only when they are first accessed.</li><li>Value Storage: After its initial calculation, the lazy variable retains its value and does not recompute on subsequent accesses.</li><li>Optimal for Expensive Operations: Ideal for values that require considerable resources to compute and are not immediately needed.</li><li>Thread Safety Concerns: Lazy variables are not thread-safe by default, which means care must be taken when using them in a multithreaded context.</li></ol><pre>import UIKit<br><br>class PhotoEditor {<br>    var image: UIImage<br><br>    // Lazy property for processed image<br>    lazy var processedImage: UIImage? = {<br>        return processImage(image)<br>    }()<br><br>    init(image: UIImage) {<br>        self.image = image<br>    }<br><br>    private func processImage(_ image: UIImage) -&gt; UIImage? {<br>        print(&quot;Processing image...&quot;)<br>        // Imagine a complex image processing task here<br>        // For example, applying a filter or analyzing the image<br>        // This operation is resource-intensive and time-consuming<br>        return image<br>    }<br>}<br><br>let rawImage = UIImage(named: &quot;sample.jpg&quot;)<br>let editor = PhotoEditor(image: rawImage!)<br><br>// The processedImage is not created until it&#39;s explicitly accessed<br>print(&quot;Before accessing processedImage&quot;)<br>let filteredImage = editor.processedImage<br>print(&quot;After accessing processedImage&quot;)</pre><p>The processImage function simulates a complex image processing task. This property is marked as lazy which means processImage will only be called (and the image processed) the first time processedImage is accessed.</p><p>This setup ensures that the heavy processing task is only performed if and when necessary, saving valuable resources and improving the app’s performance.</p><h3>Understanding Computed Properties</h3><p>Unlike lazy variables, computed properties do not store a value. Instead, they provide a getter and an optional setter to indirectly retrieve and set values.</p><h3>Characteristics of Computed Properties</h3><ol><li>Dynamic Calculation: They recalculate their value every time they’re accessed.</li><li>No Value Storage: Computed properties do not store the computed value.</li><li>Reflect Changing State: Useful when the property value depends on other variables and can change over time.</li><li>Thread Safety: Computed properties are just calculations and don’t have inherent thread safety issues, but the properties they rely on might.</li></ol><pre>class Rectangle {<br>    var width: Double<br>    var height: Double<br><br>    var area: Double {<br>        get {<br>            return width * height<br>        }<br>        set {<br>            width = sqrt(newValue)<br>            height = sqrt(newValue)<br>        }<br>    }<br><br>    init(width: Double, height: Double) {<br>        self.width = width<br>        self.height = height<br>    }<br>}</pre><p>Here, area is a computed property. It calculates the area based on width and height every time it&#39;s accessed.</p><h3>Conclusion</h3><p>Lazy variables are your go-to for resource-intensive initializations that may not be immediately required, while computed properties are ideal for values that depend on other changing variables. Mastering these concepts will enable you to write more efficient, clean, and maintainable Swift code.</p><h3>Further Reading</h3><ul><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/properties/#Computed-Properties">Swift Documentation for Computed Properties</a></li><li><a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/properties/#Lazy-Stored-Properties">Swift Documentation for Lazy Variables</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35fd323cbbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes and Structs in Swift]]></title>
            <link>https://mehrdad-ahmadian.medium.com/classes-and-structs-in-swift-75aed1adb321?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/75aed1adb321</guid>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 21:36:37 GMT</pubDate>
            <atom:updated>2024-01-17T21:36:37.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1QE237KU5aqAXuh5AKXag.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Nathan Dumlao</a> on <a href="https://unsplash.com/photos/empty-chairs-in-theater-ewGMqs2tmJI?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In Swift, the choice between a class and a struct is a fundamental decision every developer faces. While they share some similarities, understanding their differences is essential for writing robust and efficient Swift applications. This article dives deep into these two core concepts, providing real-life examples to illustrate their practical applications.</p><h3>Definition and Syntax</h3><ul><li><strong>Classes</strong> are reference types. They support inheritance, allowing one class to inherit from another.</li><li><strong>Structs</strong> are value types and come with a default memberwise initializer. They do not support inheritance.</li></ul><pre>class User {<br>    var name: String<br>    var age: Int<br><br>    // Class initializer<br>    init(name: String, age: Int) {<br>        self.name = name<br>        self.age = age<br>    }<br><br>    // Other methods can be added here<br>}</pre><p>Swift automatically provides a <strong>memberwise initializer</strong> for structs, allowing easy initialization of their properties.</p><pre>struct Point {<br>    var x: Double<br>    var y: Double<br>}<br><br>let point = Point(x: 1.0, y: 2.0)  // Using the default memberwise initializer</pre><h3>Key Differences</h3><p><strong>Inheritance:</strong> Only classes support inheritance. This allows classes to inherit properties, methods, and other characteristics from another class.</p><pre>class Vehicle {<br>    var speed = 0<br>}<br><br>class Car: Vehicle {<br>    var wheels = 4<br>}<br><br>let car = Car()<br>car.speed = 60  // Inherited property</pre><p><strong>Type (Reference vs Value):</strong> Classes are reference types, meaning they’re passed around as references to the same shared data. Structs are value types, copied when they’re passed around in your code.</p><p><strong>Classes (Reference Type)</strong></p><ul><li>Allocated in the heap and referenced by pointers.</li><li>Multiple references to a class instance share the same data.</li></ul><pre>class User {<br>    var name: String<br>    init(name: String) { self.name = name }<br>}<br><br>let user1 = User(name: &quot;Alice&quot;)<br>let user2 = user1  // user2 is a reference to the same instance<br>user2.name = &quot;Bob&quot;<br><br>print(user1.name)  // Outputs &quot;Bob&quot;</pre><p><strong>Structs (Value Type)</strong></p><ul><li>Copied when passed around in code.</li><li>Each instance keeps a unique copy of its data.</li></ul><pre>struct Point {<br>    var x: Double<br>    var y: Double<br>}<br><br>var point1 = Point(x: 1.0, y: 2.0)<br>var point2 = point1  // point2 is a copy of point1<br>point2.x = 3.0<br><br>print(point1.x)  // Outputs 1.0</pre><p><strong>Memory Management:</strong> Classes use reference counting (ARC) for memory management, while structs do not, as they’re typically stored on the stack.</p><p><strong>Classes</strong></p><ul><li>Managed through Automatic Reference Counting (ARC).</li><li>ARC tracks and cleans up objects that are no longer needed.</li></ul><pre>class Message {<br>    var content: String<br>    init(content: String) { self.content = content }<br>}<br><br>var message1: Message? = Message(content: &quot;Hello&quot;)<br>var message2 = message1  // Both references point to the same object<br><br>message1 = nil<br>// message2 still keeps the Message instance alive</pre><p><strong>Structs</strong></p><ul><li>Structs do not use ARC since they are value types.</li><li>Typically stored on the stack, leading to faster allocation and deallocation.</li></ul><pre>struct Temperature {<br>    var celsius: Double<br>}<br><br>// When a struct is passed or assigned, it&#39;s copied.<br>var temp1 = Temperature(celsius: 37.0)<br>var temp2 = temp1<br>// temp2 is a separate copy</pre><p><strong>Memberwise Initializer:</strong> In Swift, structs have a special feature called the memberwise initializer. This is a default initializer provided by Swift that allows you to initialize the member properties of new struct instances. <br>Classes on the other hand, do not receive a default memberwise initializer. This means you must provide your own initializer if your class has properties that need initial values.</p><h3>Conclusion</h3><p>In Swift, the choice between a class and a struct depends on the requirements of your data structure. Understanding the nuances of inheritance, type differences (reference vs. value), memory management, and the convenience of memberwise initializers guides you to make effective and efficient design decisions in your Swift applications.</p><h3>Further Reading</h3><ul><li>Swift Programming Language Guide: <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/classesandstructures/">Official Documentation</a></li><li>Choosing Between Structures and Classes: <a href="https://developer.apple.com/documentation/swift/choosing-between-structures-and-classes">Official Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75aed1adb321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Stored Properties, Computed Properties and Methods in Swift]]></title>
            <link>https://mehrdad-ahmadian.medium.com/understanding-stored-and-computed-properties-in-swift-e61cf90bd881?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e61cf90bd881</guid>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 06:19:37 GMT</pubDate>
            <atom:updated>2024-01-16T16:26:36.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRazbr-BAMjY_mEWtZhcgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@raymondrasmusson?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Raymond Rasmusson</a> on <a href="https://unsplash.com/photos/plastic-organizer-with-labels-7EhAf2dBthg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Swift, Apple’s powerful and intuitive programming language, offers a variety of ways to store and manage data within your applications. Among these, stored properties and computed properties are fundamental concepts every Swift developer should be familiar with. In this article, we’ll dive into the differences between stored and computed properties as well as methods, providing clear definitions and examples to illustrate their use and functionalities.</p><h3>Stored Properties</h3><p>Stored properties are the most straightforward kind of property in Swift. As the name suggests, a stored property stores a constant or variable as part of an instance of a class or a structure. This means that every instance of that class or structure will have its own copy of the stored property, maintaining its own state.</p><h4>Use Cases</h4><p>Stored properties are used when you need to keep track of state or data that is unique to each instance. They are the go-to for storing static, unchanging data, or data that changes only under specific conditions controlled by the program. They can be either variable (var) or constant (let) properties</p><pre>class Car {<br>    let make: String<br>    let model: String<br>    var mileage: Int<br><br>    init(make: String, model: String, mileage: Int) {<br>        self.make = make<br>        self.model = model<br>        self.mileage = year<br>    }<br>}</pre><p>In this example, make , model and mileage are stored properties of the Car class. Each Car instance will have its own stored properties.</p><h3>Computed Properties</h3><p>Computed properties don’t store a value. Instead, they provide a getter and optionally a setter to indirectly retrieve and set other properties and values. Computed properties calculate a value every time they are accessed.</p><h4>Use Cases</h4><p>Computed properties are used for calculations or transformations that should be encapsulated within a property. They are particularly useful when the calculated value is dependent on other properties and when this value needs to be accessed frequently in a way that is conceptually similar to accessing a simple property.</p><pre>struct Rectangle {<br>    var width: Double<br>    var height: Double<br>    var area: Double {<br>        return width * height<br>    }<br>}<br>let rectangle = Rectangle(width: 5.0, height: 10.0)<br>print(rectangle.area) // Output: 50.0</pre><p>Here, area is a computed property in the Rectangle structure. It calculates the area of the rectangle every time it is accessed, based on the current width and height properties.</p><h3>When to Use Computed Properties vs Methods</h3><h4>Computed Properties</h4><p>Best for simple calculations that are accessed like properties. E.g., calculating a fullName from firstName and lastName.</p><pre>struct Person {<br>    var firstName: String<br>    var lastName: String<br>    var fullName: String {<br>        return &quot;\(firstName) \(lastName)&quot;<br>    }<br>}</pre><h4>Methods</h4><p>Use for more complex operations or when you need to pass parameters.</p><pre>struct Rectangle {<br>    var width: Double<br>    var height: Double<br><br>    // Method to check if another rectangle can fit inside this one<br>    func canFitRectangle(withWidth otherWidth: Double, andHeight otherHeight: Double) -&gt; Bool {<br>        // Check both orientations: other rectangle could be rotated<br>        let canFitNormally = otherWidth &lt;= width &amp;&amp; otherHeight &lt;= height<br>        let canFitRotated = otherHeight &lt;= width &amp;&amp; otherWidth &lt;= height<br>        return canFitNormally || canFitRotated<br>    }<br>}<br><br>// Example usage<br>let myRectangle = Rectangle(width: 10.0, height: 5.0)<br>let canFit = myRectangle.canFitRectangle(withWidth: 3.0, andHeight: 4.0)  // Returns true<br>let cannotFit = myRectangle.canFitRectangle(withWidth: 6.0, andHeight: 8.0)  // Returns false</pre><h4>Use a Stored Property when:</h4><ul><li>To maintain state or data unique to each instance.</li><li>Ideal for static data or information that changes under controlled conditions.</li></ul><h4>Use a Computed Property when:</h4><ul><li>The value is derived from other properties.</li><li>No parameters are needed to calculate the value.</li><li>You want to provide a simpler and more property-like syntax for accessing data.</li></ul><h4>Use a Method when:</h4><ul><li>The operation involves a complex process or significant computation.</li><li>You need to pass parameters to influence the behaviour of the method.</li><li>The task does not conceptually relate to getting or setting a property.</li></ul><h3>Conclusion</h3><p>Understanding the differences and appropriate use cases for stored properties, computed properties, and methods is key to writing efficient, clear, and organized Swift code. Stored properties are the backbone for data storage, computed properties offer dynamic data access, and methods encapsulate functionality and complex operations. Mastering these concepts will significantly enhance your capabilities as a Swift developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e61cf90bd881" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Access Control: A Developer’s Guide to open, public, internal, fileprivate and private]]></title>
            <link>https://mehrdad-ahmadian.medium.com/swift-access-control-a-developers-guide-to-open-public-internal-fileprivate-and-private-79d2dd595287?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d2dd595287</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 05:58:03 GMT</pubDate>
            <atom:updated>2024-01-15T05:58:03.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alC1x2DupxRN3Al6zmJXHg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Kyle Glenn</a> on <a href="https://unsplash.com/photos/white-and-red-do-not-enter-signage-dGk-qYBk4OA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Swift’s access control system is a fundamental aspect of the language, providing mechanisms to restrict the scope of entities like classes, structures, and functions. This feature is crucial for writing secure, well-structured code. In this comprehensive guide, we’ll explore Swift’s five levels of access control: open, public, internal, fileprivate and private, along with their practical applications and differences.</p><h3>What is Access Control?</h3><p>Access control in Swift is a way to specify who can access certain parts of your code. It’s about encapsulation and hiding the internal workings of your code, which leads to better code design and enhances security.</p><h3>What is a Module?</h3><p>A module in Swift refers to a single unit of code distribution — a framework, an application, or a library that’s built and shipped as a single entity. In simpler terms, a module can be seen as a packaged codebase. For example, your iOS app is a module, and each external framework or library you use, like UIKit or Foundation, is also a module.</p><h3>Module Significance in Access Control:</h3><p>The concept of a module is central to Swift’s access control. Access levels like public, open, internal, fileprivate, and private determine how entities (classes, structures, functions, etc.) can be accessed within and outside a module. Understanding the boundaries of a module helps in deciding which access level to use for different parts of your code. Now let’s take a closer look at each one of them:</p><h3>Open and Public Access: Frameworks and Libraries</h3><p>Open and public access levels are predominantly used when developing frameworks or libraries, such as CocoaPods.</p><p><strong>Open Access:</strong> The highest access level in Swift, allowing classes and class members to be subclassed and overridden outside of their defining module. Ideal for creating extensible frameworks.</p><pre>open class NetworkManager {<br>    open func fetchData(from url: URL) {<br>        // Implementation to fetch data<br>    }<br>}<br><br>// In another module<br>class CustomNetworkManager: NetworkManager {<br>    override func fetchData(from url: URL) {<br>        // Custom implementation<br>    }<br>}</pre><p><strong>Public Access:</strong> Enables entities to be accessible outside their module but restricts subclassing and overriding to within the module.</p><pre>public class NetworkRequestHandler {<br>    public init() {}<br><br>    public func sendRequest(_ request: URLRequest, completion: @escaping (Data?, Error?) -&gt; Void) {<br>        // Implementation to send a network request<br>    }<br>}<br><br>// Usage in an external module (like a different app)<br>let requestHandler = NetworkRequestHandler()<br>let urlRequest = URLRequest(url: URL(string: &quot;https://example.com&quot;)!)<br>requestHandler.sendRequest(urlRequest) { data, error in<br>    // Handle response<br>}</pre><p><strong>Key Differences:</strong> Open access allows subclassing and overriding outside the module, while public access does not.</p><p><strong>Usage:</strong> Rarely needed in single-module applications; essential in multi-module projects like frameworks or libraries.</p><h4>Open and Public Access: A UIKit Subclassing Perspective</h4><p>To truly grasp the difference between open and public access levels in Swift, let&#39;s consider a common scenario in iOS development involving UIKit, Apple&#39;s framework for building user interfaces.</p><ul><li><strong>UIKit and Module Context:</strong> UIKit is a framework, which in Swift terms, is a module. It consists of many classes like UIViewController, UIView, etc., that are designed to be subclassed and customized.</li></ul><ol><li>Open Access with UIKit:<br>Open access level is frequently used in UIKit. It allows developers to subclass UIKit classes in their own apps (modules). For instance, UIViewController and UIView are open, enabling you to create subclasses like MyCustomViewController or MyCustomView.</li></ol><pre>// UIKit<br>open class UIViewController {<br>    // ...implementation...<br>}<br><br>// Your App<br>class MyCustomViewController: UIViewController {<br>    // Your custom implementation<br>}</pre><p>2. Public Access and its Limitation in Subclassing:<br>Open access level is frequently used in UIKit. It allows developers to subclass UIKit classes in their own apps (modules). For instance, UIViewController and UIView are open, enabling you to create subclasses like MyCustomViewController or MyCustomView.</p><pre>// Hypothetical UIKit with Public UIViewController<br>public class UIViewController {<br>    // ...implementation...<br>}<br><br>// Your App<br>class MyCustomViewController: UIViewController { // Error: Can&#39;t subclass a public class<br>    // ...your custom implementation...<br>}</pre><h3>Internal Access: The Default Choice</h3><p>In Swift, internal access is the default access level, automatically applied when no explicit access level is specified. This implicit behaviour plays a significant role in how we structure and write our Swift code.</p><h4>Understanding Implicit Internal Access</h4><p>When you declare a class, struct, function, property, or any other entity in Swift without specifying an access level, it is internal by default. This means that the entity is accessible from any file within the same module but not from outside the module.<br><strong>Why Implicit?:</strong> Swift assumes internal access to reduce verbosity in your code. Since most components within an app or framework need to interact with each other within the same module, making internal the default level streamlines code writing.</p><pre>class UserAccountManager {<br>    var currentUser: User<br>    func login(with credentials: Credentials) {<br>        // Implementation for login<br>    }<br>}</pre><p>In this example, UserAccountManager, currentUser, and login method are all internal by default. They can be accessed from any file within the same module but not from outside it.<br><strong>Application:</strong> internal access is ideal for standard application development, where most of the components need to interact with each other within the same app (module).<br><strong>Best Practice:</strong> By relying on this default behavior, you can write clean, concise code without unnecessary repetition of access level keywords, focusing instead on the core functionality of your components.</p><h3>Fileprivate and Private Access: Encapsulation within a File or Declaration</h3><p>Swift’s fileprivate and private access levels provide developers with precise control over their code&#39;s accessibility, playing a crucial role in encapsulation and data protection.</p><h4>fileprivate Access</h4><p>fileprivate restricts the use of an entity to the same source file. This is particularly useful when you have multiple types or extensions in a file that need to interact closely but you want to prevent access from other files.</p><p>Imagine you are developing a feature in your app that deals with user profiles:</p><pre>fileprivate struct UserProfile {<br>    var username: String<br>    var email: String<br>}<br><br>fileprivate enum ValidationType {<br>    case username, email<br>}<br><br>fileprivate class Validator {<br>    static func validate(_ profile: UserProfile, for type: ValidationType) -&gt; Bool {<br>        switch type {<br>        case .username:<br>            return profile.username.count &gt;= 3<br>        case .email:<br>            return profile.email.contains(&quot;@&quot;)<br>        }<br>    }<br>}<br><br>class ProfileManager {<br>    func createProfile(username: String, email: String) -&gt; Bool {<br>        let userProfile = UserProfile(username: username, email: email)<br>        return Validator.validate(userProfile, for: .username) &amp;&amp;<br>               Validator.validate(userProfile, for: .email)<br>    }<br>}</pre><p>Here, UserProfile, ValidationType, and Validator are all marked as fileprivate. They are accessible within the ProfileManager class and can interact with each other within the same file. This setup allows for shared functionality while keeping it hidden from other parts of the app.</p><h4>Private Access</h4><p>private access is the most restrictive, limiting the use of an entity to its enclosing declaration (like a class, struct, or enum) and to extensions of that declaration that are in the same file.</p><p>Consider a scenario where you’re implementing a caching mechanism:</p><pre>class CacheManager {<br>    private var cache: [String: Data] = [:]<br><br>    func setData(_ data: Data, for key: String) {<br>        cache[key] = data<br>    }<br><br>    func getData(for key: String) -&gt; Data? {<br>        return cache[key]<br>    }<br>}<br><br>extension CacheManager {<br>    func clearCache() {<br>        cache.removeAll()<br>    }<br>}</pre><p>In this example, the cache property is marked as private. It is only accessible within CacheManager and its extension. This ensures that the cache&#39;s internal storage mechanism is not accessible or modifiable from outside CacheManager, adhering to good encapsulation practices.</p><p>In general, a private entity is accessible only within its declaring type and any extensions of that type in the same file. It is not accessible in other types or extensions outside its declaring type, even if they are in the same file.</p><p><strong>Key Differences:<br></strong>fileprivate allows access within the entire file, applicable to any type or extension in that file.<br>Private restricts access strictly to the declaring type and its extensions within the same file.</p><h3>Best Practices for Using Access Control</h3><ol><li><strong>Start Conservatively:</strong> Begin with private or fileprivate and escalate access as needed.</li><li><strong>Understand Context:</strong> Use open and public primarily in frameworks or libraries; internal, fileprivate, and private are usually sufficient for single-module applications.</li><li><strong>Documentation:</strong> Clearly document public interfaces, as they’re accessible outside your module.</li></ol><h3>Conclusion</h3><p>Swift’s access control levels offer a powerful toolkit for structuring code effectively. By understanding and appropriately applying these levels, developers can create robust, maintainable, and secure applications or frameworks.</p><p>Remember, the right access level depends on the specific needs of your codebase and the context in which you’re working. Whether building a complex framework or a simple app, Swift’s access control is there to ensure your code’s integrity.</p><h3>Further Reading</h3><p>For more in-depth information, check out the Swift documentation on <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/accesscontrol/">access control</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d2dd595287" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing Arrays — A Swift Solution for Coding Interviews]]></title>
            <link>https://mehrdad-ahmadian.medium.com/analyzing-arrays-a-swift-solution-for-coding-interviews-de46079fe7b3?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/de46079fe7b3</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 20:16:28 GMT</pubDate>
            <atom:updated>2024-01-04T20:16:28.014Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analyzing Arrays — A Swift Solution for Coding Interviews</h3><figure><img alt="Photo by &lt;a href=”https://unsplash.com/@happy_lee?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash&quot;&gt;Happy Lee&lt;/a&gt; on &lt;a href=”https://unsplash.com/photos/a-rack-of-basketballs-with-different-colors-on-them-Ep_NHbX2Ae8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash&quot;&gt;Unsplash&lt;/a&gt;" src="https://cdn-images-1.medium.com/max/1024/1*uJH53TdcI8wS0t8EnB8akw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@happy_lee?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Happy Lee</a> on <a href="https://unsplash.com/photos/a-rack-of-basketballs-with-different-colors-on-them-Ep_NHbX2Ae8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the realm of coding interviews, one often encounters unique challenges that test both algorithmic thinking and coding prowess. A fascinating problem is finding the lowest index of the highest modulo value in an array of integers. This article delves into a Swift solution for this intriguing problem, offering insights that are invaluable for both aspiring and experienced software developers.</p><h3>The Problem Statement</h3><p>Imagine you are given a 1-based array of integers arr[n]. Your task is to compute the value of arr[i] to the power of arr[i + 1], modulo 10^9+7, for each element arr[i] where 1≤ <em>i </em>&lt;<em>n</em>. The goal is to find the lowest index that yields the highest modulo value.</p><p>For example, consider arr = [1, 2, 3]. The output should be 2, because:</p><ul><li>1^2 mod 1000000007 =1</li><li>2^3 mod 1000000007 = 8</li></ul><h3>Swift Solution Explained</h3><p>The solution in Swift involves two primary components: iterating through the array to calculate the modular exponentiation and finding the maximum of these values. Here’s a step-by-step guide:</p><h3>1. Function Definition:</h3><p>We define a function raisingPower(arr: [Int]) -&gt; Int, which takes an array of integers as input and returns the index of the highest modulo value.</p><h3>2. Modular Exponentiation:</h3><p>A crucial part of the solution is efficiently computing a^b mod <em>m</em> (modular exponentiation). We use a helper function, modularPow, to achieve this without encountering large number handling issues.</p><h3>3. Iterating Through the Array:</h3><p>We loop through the array, applying the modularPow function to each adjacent pair of elements, and keep track of the maximum value and its corresponding index.</p><h3>4. Returning the Result:</h3><p>Finally, the function returns the index (1-based) of the maximum modulo value obtained</p><pre>func raisingPower(arr: [Int]) -&gt; Int {<br>    let mod = 1000000007<br>    var maxIndex = 0<br>    var maxValue = 0<br><br>    for i in 0..&lt;arr.count - 1 {<br>        let result = modularPow(base: arr[i], exponent: arr[i + 1], modulus: mod)<br>        if result &gt; maxValue {<br>            maxValue = result<br>            maxIndex = i<br>        }<br>    }<br><br>    return maxIndex + 1<br>}<br><br>func modularPow(base: Int, exponent: Int, modulus: Int) -&gt; Int {<br>    if modulus == 1 { return 0 }<br>    var result = 1<br>    var baseMod = base % modulus<br>    var exp = exponent<br><br>    while exp &gt; 0 {<br>        if exp % 2 == 1 {<br>           result = (result * baseMod) % modulus<br>        }<br>        exp /= 2<br>        baseMod = (baseMod * baseMod) % modulus<br>    }<br><br>    return result<br>}</pre><h3>Complexity Analysis</h3><h3>Time Complexity:</h3><p>The time complexity of the solution is <em>O</em>(<em>n </em>log exp), where n is the number of elements in the array and exp is the exponent value. This efficiency is achieved through the use of binary exponentiation in the modularPow function.</p><h3>Space Complexity:</h3><p>The space complexity is <em>O</em>(1), as the solution uses a constant amount of space, irrespective of the input size.</p><h3>Conclusion</h3><p>This problem is a classic example of combining mathematical concepts with efficient programming techniques. The Swift solution demonstrates the importance of understanding modular arithmetic and binary exponentiation in solving complex problems. Such challenges are common in coding interviews and require a blend of theoretical knowledge and practical coding skills.</p><h3>Further Reading</h3><p>For those interested in diving deeper, consider exploring topics like number theory, algorithmic complexity, and advanced Swift programming techniques. Understanding these concepts can significantly enhance your problem-solving toolkit, especially for competitive programming and technical interviews.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de46079fe7b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Data Security in SwiftUI: From UserDefaults to Keychain]]></title>
            <link>https://mehrdad-ahmadian.medium.com/enhancing-data-security-in-swiftui-from-userdefaults-to-keychain-631dfeba5b84?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/631dfeba5b84</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[keychain]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 05:51:43 GMT</pubDate>
            <atom:updated>2023-12-24T05:51:43.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2J9VrzJjY3TJTtH0JJ77A.jpeg" /><figcaption>UserDefaults to Keychain</figcaption></figure><h3>Introduction</h3><p>In mobile applications, protecting user data is paramount. This article explores two methods of data storage in SwiftUI apps: UserDefaults and Keychain. We’ll start with the insecure UserDefaults method and then shift to the more secure Keychain approach.</p><h3>Part 1: Storing Data with UserDefaults</h3><h4><strong>What is UserDefaults?</strong></h4><ul><li>UserDefaults is a simple, lightweight mechanism for persisting user preferences and settings.</li><li>It’s not designed for storing sensitive data, as it lacks encryption.</li></ul><h4><strong>Implementing UserDefaults in SwiftUI</strong></h4><ul><li>We start by creating a SwiftUI view with a TextField and a &quot;Save&quot; button.</li><li>The entered data is stored in UserDefaults upon button tap.</li></ul><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var sensitveData = &quot;&quot;<br>    <br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Enter Sensitive Data&quot;, text: $sensitveData)<br>                .textFieldStyle(.roundedBorder)<br>                .padding()<br>            <br>            Button(&quot;Save Data&quot;) {<br>                // Insecure Storage<br>                UserDefaults.standard.setValue(sensitveData, forKey: &quot;SensitiveData&quot;)<br>            }<br>        }<br>        .padding()<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><h4>The Security Flaw</h4><p>Data stored in UserDefaults can be easily accessed and is not encrypted. Tools like <a href="https://macroplant.com/iexplorer"><strong>iExplorer</strong></a> can be used to view this data, demonstrating its vulnerability.</p><h3>Part 2: Securing Data with Keychain</h3><p><strong>Why Keychain?</strong></p><ul><li>Keychain’s Security Features</li><li>Keychain is designed for storing sensitive data such as passwords and tokens.</li><li>It encrypts data and offers various accessibility options.</li></ul><p><strong>Transitioning to Keychain</strong></p><ul><li>We add a Keychain wrapper library to our project for easy use.</li><li>Modify the ContentView to use Keychain for data storage.</li></ul><pre>import KeychainSwift<br>import SwiftUI<br><br>struct ContentView: View {<br>    @State var sensitveData: String<br>    let keychain = KeychainSwift()<br>    <br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Enter Sensitive Data&quot;, text: $sensitveData)<br>                .textFieldStyle(.roundedBorder)<br>                .padding()<br>            <br>            Button(&quot;Save Data&quot;) {<br>                // Securing Data with Keychain<br>                keychain.set(sensitveData, forKey: &quot;SensitiveData&quot;, withAccess: .accessibleWhenUnlocked)<br>            }<br>        }<br>        .padding()<br>    }<br>}</pre><p><strong>Loading Data on App Launch</strong></p><ul><li>Fetch sensitive data from Keychain in the app’s entry point and pass it to ContentView.</li></ul><pre>import SwiftUI<br>import KeychainSwift<br><br>@main<br>struct Keychain_ExampleApp: App {<br>    let keychain = KeychainSwift()<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            <br>            let sensitiveData = keychain.get(&quot;SensitiveData&quot;) ?? &quot;&quot;<br>            ContentView(sensitveData: sensitiveData)<br>        }<br>    }<br>}</pre><h4>The Enhanced Security</h4><ul><li>Data stored in Keychain is encrypted and not accessible through file-browsing tools.</li><li>This demonstrates the increased security of using Keychain over UserDefaults.</li></ul><h3>Conclusion</h3><p>Transitioning from UserDefaults to Keychain in SwiftUI apps significantly enhances data security. By implementing Keychain, developers can ensure that sensitive user data is stored safely and is less vulnerable to unauthorized access.</p><h3>Additional Resources</h3><ul><li><a href="https://github.com/evgenyneu/keychain-swift">KeychainSwift Library</a></li><li><a href="https://developer.apple.com/documentation/security/keychain_services/">Apple’s Keychain Services Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=631dfeba5b84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding map, flatMap, and compactMap in Swift]]></title>
            <link>https://mehrdad-ahmadian.medium.com/understanding-map-flatmap-and-compactmap-in-swift-eacafc38fb61?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eacafc38fb61</guid>
            <category><![CDATA[xcod]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[flatmap]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 02:14:18 GMT</pubDate>
            <atom:updated>2023-12-24T02:14:18.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK5uXtsB8BgHYnE8NZcUBg.jpeg" /><figcaption>map, flatMap, and compactMap</figcaption></figure><p>Swift, Apple’s powerful and intuitive programming language, has a rich set of features that make it a favorite among iOS and macOS developers. Among these features are three higher-order functions that are essential for efficient array manipulation: map, flatMap, and compactMap. In this article, we&#39;ll dive into each of these functions, explore their uses, and see them in action with practical examples.</p><h3>The Power of map</h3><p>The map function in Swift is a straightforward yet powerful tool for transforming arrays. It takes each element in an array, applies a given function, and returns a new array of the transformed elements.</p><h3>Example: Squaring Numbers</h3><p>Consider an array of numbers. If we want to square each number, map makes this process concise and clean.</p><pre>let numbers = [1, 2, 3, 4, 5]<br>let squaredNumbers = numbers.map { $0 * $0 }<br>// squaredNumbers is [1, 4, 9, 16, 25]</pre><h3>Unwrapping Collections with flatMap</h3><p>While map is great for simple transformations, flatMap shines when dealing with nested arrays or optional values. It not only applies a transformation but also flattens the resulting collections into a single array.</p><h3>Example: Flattening an Array of Arrays</h3><p>Imagine you have an array of arrays, and you need to merge them into a single array. flatMap does this elegantly:</p><pre>let arrayOfArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]<br>let flattenedArray = arrayOfArrays.flatMap { $0 }<br>// flattenedArray is [1, 2, 3, 4, 5, 6, 7, 8, 9]</pre><h3>Filtering with compactMap</h3><p>Finally, compactMap is similar to map but with a twist: it removes any nil values from the resulting array. This is especially useful when dealing with optional values.</p><h3>Example: Converting Strings to Integers</h3><p>In situations where a conversion might fail (like turning a string into an integer), compactMap ensures that only successful conversions are kept:</p><pre>let mixedArray = [&quot;1&quot;, &quot;two&quot;, &quot;3&quot;, &quot;four&quot;]<br>let integersArray = mixedArray.compactMap { Int($0) }<br>// integersArray is [1, 3]</pre><h3>Conclusion</h3><p>Understanding when and how to use map, flatMap, and compactMap can significantly enhance your Swift code&#39;s readability and efficiency. map is your go-to for simple transformations, flatMap for dealing with nested collections or optionals, and compactMap for filtering out unwanted nil values. Mastering these functions will make your journey with Swift more enjoyable and productive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eacafc38fb61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS FAANG Interview Question: Finding the Closest Parent View of Two UIViews]]></title>
            <link>https://mehrdad-ahmadian.medium.com/ios-faang-interview-question-finding-the-closest-parent-view-of-two-uiviews-c62f388f6f79?source=rss-f8fe1c4a605d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c62f388f6f79</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[ios-interview-question]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mehrdad Ahmadian]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 01:59:29 GMT</pubDate>
            <atom:updated>2023-12-22T01:59:29.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-87pPsbH6XOCxIkqXt4ygw.png" /><figcaption>Closest Parent View</figcaption></figure><h3>The Interview Question</h3><p>In a technical interview at a FAANG company, I encountered the following question: “Given two UIView objects within the view hierarchy of an iOS application, how would you determine the closest shared superview?&quot; This question tests your ability to navigate and manipulate view hierarchies, a fundamental skill in iOS development.</p><h3>Understanding the Problem</h3><p>By looking at the question we’re trying to solve, we can map this problem to finding the lowest common ancestor in a binary tree but applied to UIViews in iOS. The goal is to identify the nearest superview in the hierarchy that is a parent to both given views.</p><h3>The Solution Strategy</h3><p>The approach involves two phases: tracing the hierarchy from each view to the root, and then comparing these paths to locate the nearest common superview.</p><h4>1. Trace the Path to the Root</h4><p>For each UIView, create an array to record its path to the root view. You accomplish this by traversing up the view hierarchy, moving from each view to its superview.</p><p>Repeat this process for the second view.</p><h4>2. Identify the Closest Common Parent View</h4><p>Transform the path array of one view into a hash table for quick lookups. Then, iterate through the other view’s path array. The first element found in the hash table represents the closest shared parent view.</p><pre>func findClosestCommonParent(view1: UIView, view2: UIView) -&gt; UIView? {<br>    var path1 = [UIView]()<br>    var path2 = [UIView]()<br><br>    // Trace path for view1<br>    var currentView: UIView? = view1<br>    while let view = currentView {<br>        path1.append(view)<br>        currentView = view.superview<br>    }<br><br>    // Trace path for view2<br>    currentView = view2<br>    while let view = currentView {<br>        path2.append(view)<br>        currentView = view.superview<br>    }<br><br>    // Convert path2 into a hash table<br>    let hashTable = Set(path2)<br><br>    // Find the closest common ancestor<br>    for ancestor in path1 {<br>        if hashTable.contains(ancestor) {<br>            return ancestor<br>        }<br>    }<br><br>    return nil // No common ancestor found<br>}</pre><h3>Efficiency of the Solution</h3><p><strong>Time Complexity: </strong>This method is efficient, with a time complexity of <strong>O(n)</strong>, where n is the depth of the deeper view in the view hierarchy. The creation of the hash table and the iteration process are both linear operations.</p><p><strong>Space Complexity:</strong> The space complexity is detemined by the storage of two path arrays and one hash table, each containing up to d elements, where d is the maximum depth of the view in the hierarchy. This results in scaling to a linear space complexity of <strong>O(d)</strong>.</p><h3>Conclusion</h3><p>This iOS development problem, often presented in FAANG interviews, challenges candidates to apply their knowledge of view hierarchies and efficient algorithms such as finding the nearest common ancestor in a binary tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c62f388f6f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>