<?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 Jhon López on Medium]]></title>
        <description><![CDATA[Stories by Jhon López on Medium]]></description>
        <link>https://medium.com/@jaiversin?source=rss-d3b4a9b9d93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7ejLDjPixyoGquExuGrnrA@2x.jpeg</url>
            <title>Stories by Jhon López on Medium</title>
            <link>https://medium.com/@jaiversin?source=rss-d3b4a9b9d93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 18:10:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaiversin/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[Decoding the Coding Interview — Part 3]]></title>
            <link>https://medium.com/@jaiversin/decoding-the-coding-interview-part-3-3d9e89c66820?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d9e89c66820</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[job-search]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 21:16:05 GMT</pubDate>
            <atom:updated>2025-10-26T21:16:05.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding the Coding Interview — Part 3</h3><p>This post is part of my <em>Decoding the Coding Interview</em> series. You can find the <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-the-roadmap-6bc045fbba1c">full roadmap here</a>.</p><p>In the previous installment, we explored <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-2-7e7b23fa1730"><strong>Monotonic Stack/Queue</strong> and <strong>Merge Intervals</strong></a><strong> </strong>patterns that turn brute-force approaches into clean, structured solutions by leveraging order and boundaries.</p><p>In this article, we’ll shift focus toward two patterns that appear deceptively different but share a deep connection: <strong>Subsets (Backtracking)</strong> and <strong>Binary Search</strong>. One explores the full solution space (systematically generating all valid configurations )while the other does the opposite, efficiently pruning the search space in logarithmic time.</p><p>Backtracking strengthens your intuition for <em>exploration</em>: when to branch, when to stop, and how to manage state cleanly. Binary Search, on the other hand, sharpens your sense of <em>elimination</em>: how to define the search boundaries, construct feasibility checks, and converge to an optimal answer.</p><p>We’ll break down both patterns step by step, understanding when they apply, what variations exist, and the key questions to clarify before writing a single line of code. Each section includes examples and reasoning frameworks to help you confidently identify these patterns during your next technical interview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6qO3cMITgPKjPBH7CD_Ow.png" /><figcaption>Generated with Nano-Banana</figcaption></figure><h3>Subsets (Backtracking)</h3><p>The Subsets pattern is one of the core recursive backtracking techniques used to generate <em>all possible combinations or permutations</em> of a given set. It teaches you to think in terms of decision trees, making a choice, exploring deeper, and undoing that choice to explore alternate paths.</p><p>At its heart, <strong>backtracking</strong> is controlled recursion. You build a potential solution incrementally, and as soon as it violates a constraint or reaches completion, you either backtrack (undo the choice) or record it as a valid result.</p><p>Think of it like exploring every branch of a tree:</p><ul><li>Each node represents a decision (include or exclude an element).</li><li>Each branch is a path toward a complete combination or permutation.</li><li>The “backtrack” step is simply rewinding one decision to explore another path.</li></ul><h4><strong>Common Variations</strong></h4><p>Once you grasp the “choose, explore, un-choose” loop, you can adapt it to multiple problem types:</p><ol><li><strong>Standard Subsets</strong>: Generate all subsets from a set of <em>unique</em> elements (<a href="https://leetcode.com/problems/subsets/">LeetCode 78. Subsets</a>),</li><li><strong>Subsets with Duplicates: </strong>Handle arrays containing duplicates by sorting and skipping repeated values (<a href="https://leetcode.com/problems/subsets-ii/">LeetCode 90. Subsets II</a>).</li><li><strong>Combinations: </strong>Generate subsets of <em>fixed length</em> k (<a href="https://leetcode.com/problems/combinations/">LeetCode 77. Combinations</a>).</li><li><strong>Permutations: </strong>Generate <em>ordered</em> arrangements, where [1,2] and [2,1] are different (<a href="https://leetcode.com/problems/permutations/">LeetCode 46. Permutations</a>, <a href="https://leetcode.com/problems/permutations-ii/">LeetCode 47. Permutations II</a>)</li></ol><p>Each of these problems is simply a variation on how we define our <em>choices</em>, <em>constraints</em>, and <em>base cases</em>.</p><h4>Identifying the Pattern</h4><p>You’re likely looking at a Subsets/Backtracking problem when:</p><ol><li><strong>The Ask: </strong>The problem explicitly says “find all…” or “generate every possible…”<br> Keywords: <em>all combinations</em>, <em>all permutations</em>, <em>all subsets</em>, <em>all valid configurations</em>.</li><li><strong>The Structure: </strong>You can model the problem as a sequence of yes/no or pick/skip decisions for each element. That mental image of a branching decision tree is the giveaway.</li><li><strong>The Contrast: </strong>If the question asks for <em>the best</em> or <em>optimal</em> result (min, max, shortest, etc.), you’re likely in Dynamic Programming territory. If it asks for <em>all valid</em> results, you’re in Backtracking land.</li></ol><h4>The Key Questions Before Coding</h4><p>Before diving into recursion, clarify these four things:</p><p><strong>1. What defines a “choice”?</strong></p><ul><li>For subsets: whether to include the current element.</li><li>For combinations: which element to add next.</li><li>For permutations: which unused element to pick next.</li></ul><p><strong>2. How do we avoid invalid or duplicate solutions?</strong></p><ul><li>Use a startIndex to ensure you only move forward in the array.</li><li>Use a visited array to track elements in permutations.</li><li>Sort the input and skip duplicates (if i &gt; start &amp;&amp; nums[i] == nums[i-1] { continue }).</li></ul><p><strong>3. What are the base cases?</strong></p><ul><li>When a current path reaches completion (e.g., count == k or sum == target).</li><li>Or when continuing further would exceed constraints (e.g., sum &gt; target).</li></ul><p><strong>4. How do we manage state (“Choose → Explore → Un-choose”)?</strong></p><ul><li><em>Choose</em>: Add the element to your path.</li><li><em>Explore</em>: Recurse to the next index or decision.</li><li><em>Un-choose</em>: Remove the element to reset for the next branch.</li></ul><h4>Example: Combination Sum</h4><p>Let’s walk through <a href="https://leetcode.com/problems/combination-sum/">LeetCode 39. Combination Sum</a>. We’re asked to find all unique combinations of numbers that add up to a target, where each number can be reused.</p><pre>// Time Complexity: Exponential, roughly O(n^t), where t ≈ target.<br>// Space Complexity: O(t) for the recursion stack.<br>func combinationSum(_ candidates: [Int], _ target: Int) -&gt; [[Int]] {<br>    guard !candidates.isEmpty else { return [] }<br>    var result: [[Int]] = []<br><br>    func backtrack(_ start: Int, _ current: [Int], _ sum: Int) {<br>        // base cases<br>        if sum == target {<br>            result.append(current)<br>            return<br>        }<br>        if sum &gt; target { return }<br><br>        for i in start..&lt;candidates.count {<br>            var newCurrent = current<br>            // the choose: pick next candidate to add to current combination<br>            newCurrent.append(candidates[i])<br>            // the recursion or explore: sending i and not i + 1 as <br>            // normally we do in backtracking as we are allowed to<br>            // repeat candidates in our combination. <br>            backtrack(i, newCurrent, sum + candidates[i])<br>            // The un-choose: <br>            currentComb.removeLast()<br>        }<br>    }<br><br>    backtrack(0, [], 0)<br>    return result<br>}</pre><p>Backtracking isn’t about memorizing code templates, it’s about <em>structuring decisions</em>.<br> Define your choice, base case, and reset step clearly, and you can adapt this pattern to dozens of problems (N-Queens, Sudoku Solver, Letter Combinations, etc.).</p><p>Once you see a decision tree forming in your mind, you’ll know you’ve spotted a Backtracking problem.</p><h3>Binary Search</h3><p>If Backtracking explores <em>all possibilities</em>, <strong>Binary Search</strong> is about eliminating <em>half the possibilities</em> at every step.</p><p>It’s one of the most fundamental patterns in algorithmic reasoning: define your <em>search space</em>, pick a <em>midpoint</em>, test a <em>condition</em>, and shrink your space accordingly.</p><p>It’s not just about “searching sorted arrays”, modern interview problems use Binary Search to optimize answers over <em>ranges of values</em>, not just indices.</p><h4>Common Variations</h4><ol><li><strong>Classic Binary Search (Sorted Array): </strong>Find an element’s index in a sorted list (<a href="https://leetcode.com/problems/binary-search/">LeetCode 704. Binary Search</a>).</li><li><strong>Search for Min/Max Value: </strong>The array itself may not hold the answer — the answer lies in a numeric range defined by constraints (<a href="https://leetcode.com/problems/koko-eating-bananas/">LeetCode 875. Koko Eating Bananas</a>, <a href="https://leetcode.com/problems/split-array-largest-sum/">LeetCode 410. Split Array Largest Sum</a>).</li><li><strong>Binary Search on Answer (Parametric Search):</strong> You’re not looking for an index, but the smallest/largest value that satisfies a condition. The core trick: write a <em>feasibility function</em> (check(mid)) that tells you whether mid works.</li></ol><h4>Identifying the Pattern</h4><p>You’re likely facing a Binary Search pattern when:</p><ol><li><strong>The Input or Space Has Order: </strong>Either the array is sorted, or the possible values can be compared in increasing/decreasing order.</li><li><strong>The Problem Involves a Yes/No Decision: </strong>“Can we finish X in time Y?”, “Is k speed enough?”, “Can we split array into ≤ m subarrays?”</li><li><strong>You Can Define a Feasibility Function: </strong>A function that, for any given mid, tells you if it satisfies the condition (and guides how to shrink the search space).</li></ol><h4>The Key Questions Before Coding</h4><p>1. <strong>What is the Search Space?</strong></p><ul><li>Is it the indices of the array (0…n-1)?</li><li>Or a numeric range (1…maxValue)?</li></ul><p>2. <strong>What’s the Condition/Feasibility Function?</strong></p><ul><li>For classic search: array[mid] == target</li><li>For parametric search: check(mid) returns true/false</li></ul><p>3. <strong>How Do You Shrink the Space?</strong></p><ul><li>If condition is <em>true</em>, should we move left or right?</li><li>This defines whether you’re searching for <strong>minimum satisfying</strong> or <strong>maximum valid</strong> value.</li></ul><p>4. <strong>What’s the Return Value?</strong></p><ul><li>Sometimes left (the first true)</li><li>Sometimes right (the last true)</li></ul><p><strong>Example 1: Classic Binary Search</strong></p><pre>// Time Complexity: O(log n)<br>// Space Complexity: O(1)<br><br>var left = 0<br>var right = nums.count - 1<br><br>while left &lt;= right {<br>    let mid = (left + right) / 2<br>    if nums[mid] == target {<br>        return mid<br>    } else if nums[mid] &lt; target {<br>        left = mid + 1<br>    } else {<br>        right = mid - 1<br>    }<br>}<br>return -1 // Not found</pre><p><strong>Example 2: Binary Search on Answer — <em>Koko Eating Bananas</em></strong></p><pre>func minEatingSpeed(_ piles: [Int], _ h: Int) -&gt; Int {<br>    var left = 1<br>    var right = piles.max()!<br><br>    while left &lt;= right {<br>        let mid = (left + right) / 2<br>        if canEatAll(piles, h, mid) {<br>            right = mid - 1<br>        } else {<br>            left = mid + 1<br>        }<br>    }<br>    return left<br>}<br><br>func canEatAll(_ piles: [Int], _ h: Int, _ k: Int) -&gt; Bool {<br>    var hours = 0<br>    for pile in piles {<br>        hours += Int(ceil(Double(pile) / Double(k)))<br>    }<br>    return hours &lt;= h<br>}</pre><p>Here, the search space is Koko’s eating speed (1...maxPile), and the check function tests feasibility (whether she can finish in time).</p><p><strong>Example 3: Split Array Largest Sum</strong></p><pre>func splitArray(_ nums: [Int], _ k: Int) -&gt; Int {<br>    var left = nums.max()!<br>    var right = nums.reduce(0, +)<br><br>    func canSplit(_ mid: Int) -&gt; Bool {<br>        var pieces = 1, sum = 0<br>        for num in nums {<br>            if sum + num &gt; mid {<br>                pieces += 1<br>                sum = 0<br>            }<br>            sum += num<br>        }<br>        return pieces &lt;= k<br>    }<br><br>    while left &lt;= right {<br>        let mid = (left + right) / 2<br>        if canSplit(mid) {<br>            right = mid - 1<br>        } else {<br>            left = mid + 1<br>        }<br>    }<br>    return left<br>}</pre><p>This pattern is a perfect example of <strong>binary search over the answer</strong> — when you’re not searching through input elements but through possible outcomes.</p><p>Binary Search is less about arrays and more about <em>structured elimination</em>.<br> Once you define a monotonic condition (as x increases, condition moves from false → true or vice versa), you can narrow down the answer logarithmically.</p><p>When you spot a problem that says “minimize the maximum” or “find the smallest/largest value satisfying a condition,” think beyond sorting — think <strong>Binary Search on Answer</strong>.</p><h3>Conclusion</h3><p>Both <strong>Subsets (Backtracking)</strong> and <strong>Binary Search</strong> highlight the importance of <em>structure over syntax</em> in technical interviews. Once you understand the underlying pattern (whether you’re exploring all possibilities or narrowing down to one) the implementation becomes a matter of applying the right mental model.</p><p>Backtracking teaches you <em>systematic exploration</em> (how to manage recursion, track state, and prune decisions efficiently). Binary Search teaches you <em>systematic elimination</em> (how to define conditions and reduce uncertainty at every step).</p><p>Together, they represent two ends of the problem-solving spectrum: one expands until every possibility is explored, the other contracts until only one remains.</p><p>In the next part of this series, we’ll continue building this toolkit of mental models — transforming what seem like isolated problems into familiar patterns you can approach with clarity, precision, and confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d9e89c66820" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Coding Interview — Part 2]]></title>
            <link>https://medium.com/@jaiversin/decoding-the-coding-interview-part-2-7e7b23fa1730?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7b23fa1730</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[job-interview]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[job-hunting]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 22:20:58 GMT</pubDate>
            <atom:updated>2025-10-26T18:36:16.441Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding the Coding Interview — Part 2</h3><p>This post is part of my <em>Decoding the Coding Interview</em> series. You can find the <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-the-roadmap-6bc045fbba1c">full roadmap here</a>.</p><p>This is the second installment in my series on decoding the coding interview, where I’m unpacking the most common problem-solving patterns you’ll encounter in technical interviews. In <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-1-f36bef671b15">Part 1</a>, we explored Sliding Window and Two Pointers, two patterns that sharpen your ability to work with arrays and sequences.</p><p>In this article, we’ll turn our attention to <strong>Monotonic Stack/Queue</strong> and <strong>Merge Intervals</strong> — two patterns that may look intimidating at first but can transform brute-force O(n²) solutions into elegant O(n log n) or even O(n) strategies. These patterns frequently appear in problems about ranges, scheduling, and “next greater/smaller” computations, and mastering them will give you a strong advantage in tackling mid- to hard-level interview questions.</p><p>We’ll go step by step: understanding when these patterns apply, what variations exist, and the key decisions to clarify <em>before</em> you start coding. Along the way, I’ll include examples and snippets to ground these concepts in real-world practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JIU6yY0qxfrRYjnQq4AZ3A.png" /><figcaption>Generated by ChatGPT</figcaption></figure><h3>Monotonic Stack/Queue</h3><p>The Monotonic Stack/Queue pattern is a specialized data structure technique where elements are maintained in <strong>increasing or decreasing order</strong>. It’s a powerful tool for optimizing problems that ask for <em>next greater/smaller elements</em>, <em>span ranges</em>, or <em>sliding window maximums</em>.</p><p>Instead of scanning linearly for every element (O(n²)), the monotonic structure ensures that each element is pushed and popped at most once — leading to O(n) complexity.</p><h4>Common Variations:</h4><ol><li><strong>Monotonic Increasing Stack: </strong>Used to find the <em>next greater element </em>(<a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">LeetCode 84. Largest Rectangle in Histogram</a>).</li><li><strong>Monotonic Decreasing Stack:</strong> Used to find the <em>next smaller element </em>(<a href="https://leetcode.com/problems/daily-temperatures/">LeetCode 739. Daily Temperatures</a>)</li><li><strong>Monotonic Queue:</strong> Used in sliding window problems to maintain max/min efficiently (<a href="https://leetcode.com/problems/sliding-window-maximum/">LeetCode 239. Sliding Window Maximum</a>).</li></ol><h4>Identifying the Pattern</h4><p>To identify problems that match this pattern, look for these cues in the problem description:</p><ol><li><strong>Input Type: </strong>Usually an <strong>array</strong> of numbers.</li><li><strong>The Ask: </strong>You need to find next greater/smaller values, maintain order, or compute range-based maximums/minimums.</li><li><strong>The Constraint: </strong>A brute force approach would check in both directions (nested loops or O(n²) time complexity).</li></ol><p><strong>Your Monotonic Stack/Queue alarm should go off</strong> if you see <em>array + “next greater/smaller” or “window max/min”</em>.</p><h4>The key questions before coding</h4><p>Now you need to figure out (and even better discuss with the interviewer at the same time) four things before writing a single line of code.</p><ol><li>Stack or Queue? <strong>(The “Structure Choice”)</strong></li></ol><ul><li>Stack: Sequential problems like “next greater element”. For example, <em>LeetCode 739. Daily Temperatures</em> → Stack (we need the “next warmer day”).</li><li>Queue: Range problems like “sliding window maximum”. For example, <em>LeetCode 239. Sliding Window Maximum</em> → Queue (we need max in every window).</li></ul><p>2. Increasing or Decreasing? <strong>(The “Order”)</strong></p><p>Decide based on what you need to pop:</p><ul><li><strong>Monotonic Decreasing Stack</strong>: Pop smaller elements until you find a greater one.</li><li><strong>Monotonic Increasing Stack</strong>: Pop larger elements until you find a smaller one.</li></ul><pre>// Daily Temperatures (Monotonic Decreasing Stack)<br>for i in 0..&lt;temps.count {<br>    while !stack.isEmpty &amp;&amp; temps[i] &gt; temps[stack.last!] {<br>        let prev = stack.removeLast()<br>        res[prev] = i - prev<br>    }<br>    stack.append(i)<br>}</pre><p>3. What extra info do I need to track? <strong>(The “State”)</strong></p><p>Often you need <strong>indexes</strong>, not just values:</p><ul><li>For Daily Temperatures: Store the index of unresolved days.</li><li>For Sliding Window Maximum: Store indices to check if they’re still in the window.</li></ul><pre>// Sliding Window Maximum (Monotonic Queue)<br>for i in 0..&lt;nums.count {<br>    // Remove elements out of the window<br>    if !deque.isEmpty &amp;&amp; deque.first! &lt;= i - k {<br>        deque.removeFirst()<br>    }<br>    // Maintain decreasing order<br>    while !deque.isEmpty &amp;&amp; nums[i] &gt; nums[deque.last!] {<br>        deque.removeLast()<br>    }<br>    deque.append(i)<br>    // First window valid at i &gt;= k - 1<br>    if i &gt;= k - 1 {<br>        res.append(nums[deque.first!])<br>    }<br>}</pre><p>4. How to calculate the answer?<strong> (The “Result”)</strong></p><ul><li>For <em>Daily Temperatures</em>: The difference in indices.</li><li>For <em>Largest Rectangle in Histogram</em>: Use popped indices to compute areas.</li><li>For <em>Sliding Window Maximum</em>: The value at the front of the deque.</li></ul><p>Each variant has the same principle: Maintain monotonic order, pop invalid entries and use the remaining structure to extract the result.</p><p>By breaking down the problem into these four checkpoints, you’ll know how to shape your monotonic structure and when to pop or push elements.</p><h3>Merge Intervals</h3><p>The Merge Intervals pattern deals with problems where the input is a collection of intervals (e.g., [start, end]) and the goal is to combine or merge overlapping intervals into a smaller, consolidated set. The trick to solving almost every Merge Intervals problem is to sort the intervals by their start times. Once they are sorted, you can iterate through them and make a simple, greedy decision about whether the current interval overlaps with the previous one.</p><p>This pattern is incredibly common in interviews, especially for questions that involve scheduling, resource allocation, or analyzing overlapping time periods.</p><h4>Common Variations:</h4><ol><li>Merging Overlapping Intervals: The goal is to produce a new list of consolidated intervals.</li></ol><ul><li>The classic problem <a href="https://leetcode.com/problems/merge-intervals/">LeetCode 56. Merge Intervals</a></li><li>A variation where you insert a new interval into an already-sorted list of non-overlapping intervals <a href="https://leetcode.com/problems/insert-interval/">LeetCode 57. Insert Interval</a></li></ul><p>2. Counting for Scheduling/Allocation: The goal is to find the maximum number of concurrent events or resources needed.</p><ul><li>A fantastic problem that requires a slight twist on the pattern, often using a min-heap <a href="https://leetcode.com/problems/meeting-rooms-ii/">LeetCode 253. Meeting Rooms II</a></li></ul><p>3. Greedy Removal/Selection: The goal is to find the minimum number of removals or the maximum number of compatible events.</p><ul><li><a href="https://leetcode.com/problems/non-overlapping-intervals/">LeetCode 435. Non-overlapping Intervals</a></li></ul><h4>Identifying the Pattern</h4><p>Look for these signals in the problem description:</p><ol><li><strong>Input Type:</strong> The input is always a <strong>list or array of intervals</strong>, where each interval is represented by a <strong>start and an end point</strong> (e.g., [start, end], a custom Interval object).</li><li><strong>The Ask:</strong> The problem will involve reasoning about the <strong>relationships between these intervals</strong>. Common tasks include:</li></ol><ul><li>Merging <strong>overlapping intervals</strong>.</li><li>Counting the <strong>number of overlaps or conflicts</strong> (e.g., “how many meeting rooms are needed?”).</li><li>Finding the minimum <strong>number of removals</strong> to make the rest non-overlapping.</li><li>Finding a <strong>“free” </strong>or<strong> “available” time slot</strong> among a schedule of busy times.</li></ul><p>3. <strong>The “Tell”</strong>: The most reliable indicator is that the problem seems incredibly complex with unsorted data (requiring O(n²) comparisons) but becomes much simpler if you could process the intervals in a specific order. If you think, “this would be easy if they were sorted by their start times,” you’ve likely found a Merge Intervals problem.</p><h4>The key questions before coding</h4><p>Once you’ve identified the pattern, you must define your strategy by answering these four questions.</p><ol><li>What is the Preprocessing Step? <strong>(“The Sorting”)</strong></li></ol><p>This is the most critical question for this pattern. The answer is almost always: Sort the intervals by their start times. This is the key that enables a simple, linear scan.</p><p>2. How will I store my result? <strong>(“The Result”)</strong></p><p>What data structure will you use to build the answer?</p><ul><li>For merging problems, this is typically a new list that will hold the final, merged intervals.</li><li>For counting problems, this might just be a simple integer variable (e.g., removals, maxRooms).</li></ul><p>3. What is the exact overlap condition? <strong>(“The Overlap Condition”)</strong></p><p>Assuming the intervals are sorted by their start times, how do you define an overlap between the previous interval you’re tracking and the current interval you’re inspecting?</p><ul><li>The condition is almost always: current.start &lt;= previous.end. If the start of the current interval comes before or at the same time as the end of the previous one, they overlap.</li></ul><p>4. What is the Core Logic for the Two Cases? <strong>(“The Decision”)</strong></p><p>When you compare the current interval to the previous one (or the last one in your results), there are only two possibilities. What is the action for each?</p><p>Case 1: They Overlap. What do you do? This is the “merge” or “greedy choice” step.</p><ul><li>For merging: You update the end of the previous interval: previous.end = max(previous.end, current.end).</li><li>For counting removals: You increment your removal count and then greedily decide which interval to “keep” for the next comparison (usually the one with the smaller end time).</li></ul><p>Case 2: They Don’t Overlap. What do you do?</p><ul><li>For merging: The previous interval is finalized. You add the current interval to your results list as a new, separate interval to be compared against later.</li><li>For counting removals: The previous interval is finalized. You simply update your previous interval to be the current one.</li></ul><h3>Conclusion</h3><p>Both <strong>Monotonic Stack/Queue</strong> and <strong>Merge Intervals</strong> share a key lesson: interviews aren’t just about solving problems, they’re about recognizing structure. Once you identify the “shape” of the problem, the rest becomes systematic: pick the right structure, define the rules for pushing and popping, and let the algorithm almost write itself.</p><p>If Sliding Window and Two Pointers were about sharpening your intuition with arrays, then <strong>Monotonic Structures</strong> and <strong>Merge Intervals</strong> are about learning to <strong>trust order and constraints</strong>. They teach you to look for signals, like “next greater element” or “overlapping intervals”, and then apply a reliable framework instead of brute force.</p><p>In the next part of this series, we’ll keep expanding your toolkit with patterns that help you break down complex challenges into manageable steps. The more patterns you master, the more confident and calm you’ll feel walking into your next coding interview.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7b23fa1730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Coding Interview — Part 1]]></title>
            <link>https://medium.com/@jaiversin/decoding-the-coding-interview-part-1-f36bef671b15?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36bef671b15</guid>
            <category><![CDATA[sliding-windows]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 20:08:12 GMT</pubDate>
            <atom:updated>2025-09-04T02:48:32.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decoding the Coding Interview — Part 1</h3><p>This post is part of my <em>Decoding the Coding Interview</em> series. You can find the <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-the-roadmap-6bc045fbba1c">full roadmap here</a>.</p><p>In this article I’ll walk through the core <strong>problem-solving patterns</strong> behind Sliding Window and Two Pointers patterns, presenting:</p><ul><li>A breakdown of the pattern and how to recognize it in problems</li><li>My personal framework for solving it under interview pressure</li><li>Sample problems and links for further practice</li></ul><p>Remember, the goal is not just to pass interviews — but to develop confidence in solving new, unseen problems using reusable mental models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjQBuC3pjxMcScNXeW0itw.png" /></figure><h3>Sliding Window</h3><p>The Sliding Window pattern involves maintaining a “window” of elements (usually a subarray or substring) that grows or shrinks according to specific conditions. It’s particularly efficient for problems where you need to find a <strong>contiguous sequence</strong> that meets certain criteria.</p><p>This pattern transforms what would typically be an O(n²) or worse solution into an O(n) solution by avoiding redundant work. Instead of recalculating everything for each possible window, we incrementally update our window’s state as we slide through the data.</p><h4>Common Variations:</h4><ol><li><strong>Fixed-Size Window:</strong> The window size remains constant (<a href="https://leetcode.com/problems/maximum-average-subarray-i/">LeetCode 643. Maximum Average Subarray I</a>).</li><li><strong>Variable-Size Window:</strong> The window size changes based on a condition (<a href="https://leetcode.com/problems/minimum-size-subarray-sum/">LeetCode 209. Minimum Size Subarray Sum</a>).</li><li><strong>Dynamic Constraints: </strong>The window’s validity depends on a dynamic property (<a href="https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/">LeetCode 340. Longest Substring with At Most K Distinct Characters</a>).</li></ol><h4>Identifying the Pattern</h4><p>To identify problems that match this pattern, look for keywords and constraints in the problem description:</p><ol><li><strong>Input Type:</strong> The problem will almost always involve a linear data structure, like an <strong>array</strong>, a <strong>string</strong>, or a <strong>linked list</strong>.</li><li><strong>The Ask:</strong> You’ll be asked to find the <strong>longest</strong>, <strong>shortest</strong>, or <strong>most optimal</strong> (e.g., minimum, maximum, or containing a specific property) <strong>contiguous subarray or substring</strong>.</li><li><strong>The Constraint:</strong> There will be a constraint on this subarray/substring, often given as an integer <em>k</em>. This could be:</li></ol><ul><li>“sum is at least k”</li><li>“contains at most k distinct characters”</li><li>“can be made valid with at most k changes”</li><li>“average is greater than k”</li></ul><p>If you see <em>array/string + contiguous subproblem + constraint </em><em>k</em>, your Sliding Window alarm should go off immediately.</p><h4>The key questions before coding</h4><p>Once you’ve identified the pattern, you need to figure out four things before writing a single line of code. This is what you should be thinking about and discussing with your interviewer.</p><p>1. What data do I need to track for my window? <strong>(The “State”)</strong> What information about the current window is necessary to check its validity?</p><p>This often involves a hash map (or dictionary) but could be a simple variable. This could be a frequency map (Leetcode <a href="https://leetcode.com/problems/longest-repeating-character-replacement/description/">424. Longest Repeating Character Replacement</a>), the currentSum of the window (Leetcode <a href="https://leetcode.com/problems/minimum-size-subarray-sum/description/">209. Minimum Size Subarray Sum</a>), a Set of distinct characters (Leetcode 340 <a href="https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/">Longest Substring with At Most K Distinct Characters</a>).</p><p>2. How do I expand the window? (<strong>The “Expansion”</strong>)</p><p>This is almost always the easy part. You expand the window by moving the right pointer forward one step at a time, usually with a for or while loop.</p><p><em>Action:</em> When you expand, you must update the window’s state with the new element at the right pointer.</p><p>3. When and how do I shrink the window? (<strong>The “Contraction Condition”</strong>)</p><p>This is the most critical part of the algorithm and the key to the whole pattern. You need to define the exact condition that makes the current window invalid.</p><p>This could be <em>currentSum &gt; target</em> (Leetcode <a href="https://leetcode.com/problems/minimum-size-subarray-sum/description/">209</a>), <em>distinctCharSet.count &gt; k</em> (Leetcode 340) or <em>(windowSize — maxFrequency) &gt; k</em> (Leetcode <a href="https://leetcode.com/problems/longest-repeating-character-replacement/description/">424</a>).</p><p><em>Action:</em> When the window is invalid, you shrink it by moving the left pointer forward. When you do this, you must update the window’s state by removing the element at the left pointer.</p><p>4. How do I calculate the final result? (<strong>The “Answer”</strong>)</p><p>What are you trying to find? The answer is usually derived from the window’s size (right — left + 1).</p><ul><li>For <strong>“longest/maximum” problems</strong>: You often don’t need to shrink the window size. The final size <em>(right — left)</em> will represent the maximum size achieved, because it only ever grew when the condition was met. You can track a <em>maxLength</em> variable and update it on every valid iteration, but it’s often not necessary.</li><li>For <strong>“shortest/minimum” problems</strong>: You must find a valid window first, record its length, and then try to shrink it as much as possible while it remains valid. You’ll need a <em>minLength</em> variable that you update every time you find a new, shorter valid window.</li><li>For <strong>“count all valid subarrays” problems</strong>: Every time you have a valid window, you can calculate how many new subarrays end at the right pointer.</li></ul><p>By breaking down any potential Sliding Window problem with this four-question framework, you’ll have a clear, structured plan to build an optimal solution from scratch.</p><h3>Two Pointers</h3><p>The Two Pointers pattern involves using two pointers (usually integer indices) that move through a data structure, often in a coordinated way, until they meet or satisfy a certain condition. Unlike Sliding Window, where the pointers define a <em>range</em>, here the pointers often work independently or in relation to each other to find a pair of elements or a specific point in the data.</p><p>Problems that might naively be solved in O(n²) time (by comparing every element with every other element) can often be solved in O(n) time with a Two Pointers approach.</p><h4>Common Variations:</h4><ol><li><strong>Opposite Ends: </strong>One pointer starts at the beginning of a sorted array, and the other starts at the end. They move towards each other. This is extremely common for finding pairs that sum to a target (Leetcode <a href="https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/">167. Two Sum II — Input Array Is Sorted</a>).</li><li><strong>Fast &amp; Slow Pointers: </strong>Both pointers start at the beginning, but one moves faster than the other. This is the go-to pattern for problems involving cycles in a linked list (Leetcode <a href="https://leetcode.com/problems/linked-list-cycle/">141. Linked List Cycle</a>) or finding the middle of a list (Leetcode <a href="https://leetcode.com/problems/middle-of-the-linked-list/">876. Middle of the Linked List</a>).</li><li><strong>Same Direction (Variable Separation): </strong>Both pointers start at the beginning and move in the same direction, but with a variable gap between them. This can sometimes overlap with Sliding Window but is often used for problems like finding the “longest substring with no repeating characters” (Leetcode <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">3. Longest Substring Without Repeating Characters</a>).</li></ol><h3>Identifying the Pattern</h3><p>Look for these specific clues in the problem description. It’s subtly different from Sliding Window.</p><ol><li><strong>Input Type:</strong> Just like Sliding Window, the input is almost always a linear data structure like an <strong>array</strong> or a <strong>string</strong>. A huge signal for one specific variant is a <strong>linked list</strong>.</li><li><strong>The Ask:</strong> The goal is usually to find a <strong>pair of elements</strong>, a <strong>triplet of elements</strong> (Leetcode <a href="https://leetcode.com/problems/3sum/">15. 3Sum</a>), or a <strong>specific position/node</strong> that satisfies a <strong>condition</strong>. This is different from Sliding Window, which usually asks for a contiguous subarray.</li><li><strong>The “Tell”:</strong> The most powerful clue is that the problem can be solved by processing the data from both ends inwards, or by having one pointer that moves faster than another.</li></ol><ul><li>Is the array sorted? This is a massive hint for the “Opposite Ends” strategy (Leetcode <a href="https://leetcode.com/problems/container-with-most-water/">11. Container With Most Water</a>).</li><li>Does the problem involve finding a cycle, the middle element, or the Nth-from-last element in a linked list? This screams “Fast &amp; Slow Pointers” (Leetcode <a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End of List</a>).</li><li>Does it involve comparing elements at different positions without a fixed-size window?</li></ul><p>If you see a sorted array and need to find a pair, or you see a linked list cycle problem, your “Two Pointers” alarm should be ringing loudly.</p><h3>The key questions before coding</h3><p>Once you’ve identified the pattern, you must define your strategy by answering these four questions. This is what you should discuss with your interviewer.</p><p>1. What is my pointer strategy? (<strong>The “Setup”</strong>)</p><p>Based on the problem, which variant of the Two Pointers pattern is the best fit?</p><ul><li>“Two Sum II” Problem: The array is sorted and we need a pair. The clear strategy is <strong>Opposite Ends</strong>.</li><li>Linked List Cycle Detection: The strategy must be <strong>Fast &amp; Slow Pointers</strong>.</li><li>Other Problems: Sometimes it’s two pointers moving in the same direction. You must choose the setup first.</li></ul><p>2. How do my pointers start? (<strong>The “Initialization”</strong>)</p><p>Based on your chosen strategy, what are the exact starting positions of your pointers?</p><ul><li><strong>Opposite Ends</strong>: left = 0, right = array.count — 1.</li><li><strong>Fast &amp; Slow</strong>: slow = head, fast = head.</li></ul><p>3. What is the loop’s continuation condition? (<strong>The “Boundary”</strong>) When does the process stop?</p><p>This defines your while loop’s condition and prevents infinite loops.</p><ul><li>Opposite Ends: The loop continues while left &lt; right. If they meet or cross, we’ve checked all possible pairs.</li><li>Fast &amp; Slow: The loop continues while fast != nil &amp;&amp; fast.next != nil. If the fast pointer goes off the end of the list, there’s no cycle.</li></ul><p>4. How do my pointers move? (<strong>The “Core Logic”</strong>)</p><p>This is the heart of the algorithm. Inside the loop, what logic dictates how the pointers are updated in each iteration?</p><ul><li>Opposite Ends: This is based on comparing a currentValue (like a sum) to a targetValue.</li></ul><p>— If currentValue &lt; targetValue, you need a bigger value, so left += 1.</p><p>— If currentValue &gt; targetValue, you need a smaller value, so right -= 1.</p><p>— If currentValue == targetValue, you’ve found the solution.</p><ul><li>Fast &amp; Slow: The movement is usually fixed. slow = slow.next, fast = fast.next.next. The result comes from when/if they meet.</li></ul><p>By systematically answering these four questions, you create a complete blueprint for your algorithm. You demonstrate that you are not just guessing, but are applying a proven, structured pattern to deconstruct the problem and build an optimal solution.</p><h4>Conclusion</h4><p>This is just the start. By shifting the focus from memorizing solutions to mastering <strong>patterns</strong>, we build not only interview readiness but also deeper problem-solving intuition. In upcoming articles, I’ll continue unpacking more patterns, like Merge Intervals and Backtracking, and show how they can turn overwhelming problems into structured, solvable challenges.</p><p>If Sliding Window and Two Pointers made sense to you here, stick around — this is only the beginning of decoding the coding interview.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36bef671b15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding the Coding Interview: The Roadmap]]></title>
            <link>https://medium.com/@jaiversin/decoding-the-coding-interview-the-roadmap-6bc045fbba1c?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bc045fbba1c</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[job-hunting]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 19:17:36 GMT</pubDate>
            <atom:updated>2025-10-26T21:28:29.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Most engineers approach coding interviews the wrong way: they grind through hundreds of LeetCode problems hoping repetition will lead to mastery. I did that too — and it burned me out.</p><p>I realized I wasn’t following my own mantra: <strong>“Don’t just learn tools — learn the concepts behind them” </strong>and applied to this subject, “<strong>Don’t memorize solutions, learn the patterns behind them”</strong>.</p><p>It’s a mindset I’ve applied throughout my career and shared with mentees over the years. Whether it was mastering CocoaPods or architecting an iOS app, understanding the underlying principle — like dependency management — always unlocked the ability to adapt, pivot, and grow.</p><p>That mindset turned a stressful, endless grind into a structured, repeatable process. Instead of brute-forcing my way through problem banks, I built a framework to recognize problem types, apply the right strategies, and adapt under pressure.</p><p>This series is that framework — my playbook for tackling live coding interviews with confidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DL2mZhnR7zvW0cJvgIXt-g.png" /></figure><h3>The Roadmap</h3><p>This isn’t just a random collection of posts. Think of it as a structured course in article form.</p><h3>Part 1–4: Core Patterns</h3><p>Each article will cover <strong>2–3 fundamental problem-solving patterns</strong> engineers encounter in interviews:</p><ul><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-1-f36bef671b15">Sliding Window</a></li><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-1-f36bef671b15">Two Pointers</a></li><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-2-7e7b23fa1730">Monotonic Stack/Queue</a></li><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-2-7e7b23fa1730">Intervals</a></li><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-3-3d9e89c66820">Subsets (Backtracking)</a></li><li><a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-3-3d9e89c66820">Binary Search Variants</a></li><li>BFS &amp; DFS</li><li>Top ‘K’ Elements</li><li>Dynamic Programming essentials</li></ul><p>For each pattern, I’ll share:</p><ul><li><strong>How to recognize it</strong> in a problem statement</li><li><strong>A step-by-step framework</strong> for solving it</li><li><strong>Example problems</strong> to practice, with links</li></ul><h3>Part 5: Deep Dive on Data Structures</h3><p>Patterns only get you so far without strong foundations. This article will focus on the <strong>core data structures</strong> — arrays, trees, heaps, graphs, hash maps — and how they unlock entire problem families.</p><p>You’ll also learn how to <strong>choose the right data structure under time pressure</strong>, a key skill in live interviews.</p><h3>Part 6: Templates &amp; Cheat Sheet</h3><p>The final article will consolidate everything into a <strong>single reference</strong>:</p><ul><li>Pattern recognition checklist</li><li>Common pseudo-code templates</li><li>Decision trees for selecting the right strategy</li><li>Quick reminders for edge cases</li></ul><p>This is the piece you’ll want to bookmark before every interview.</p><h3>Why This Series?</h3><p>There are great resources out there — <a href="#">Neetcode’s roadmap</a>, <a href="#">AlgoMonster’s decision flowcharts</a>, <a href="https://www.techinterviewhandbook.org/">Tech Interview Handbook</a>. I’ve learned from them all.</p><p>But none fully clicked for me until I built my own framework. That’s why I’m sharing this: to help others move beyond <strong>memorizing</strong> and start <strong>thinking in patterns.</strong></p><h3>What’s Next?</h3><p>The first installment — <a href="https://medium.com/@jaiversin/decoding-the-coding-interview-part-1-f36bef671b15"><strong>Sliding Window &amp; Two Pointers</strong> </a>— is already live. Future posts will build from there, with links added back here as the series grows.</p><p>This isn’t about passing one interview. It’s about building <strong>confidence, adaptability, and reusable mental models</strong> you can apply in any coding challenge.</p><p>Follow along, and let’s decode the coding interview — one pattern at a time.</p><p>📌 <em>This post will be updated as new parts go live. Bookmark it to track the full series.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc045fbba1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dive deep on architectural patterns]]></title>
            <link>https://medium.com/@jaiversin/dive-deep-on-architectural-patterns-1b72a4f5e6fd?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b72a4f5e6fd</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-architecture]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 18:29:39 GMT</pubDate>
            <atom:updated>2025-08-22T03:13:55.936Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a continuation of my previous article <a href="https://medium.com/@jaiversin/decoding-ios-architectures-f9bec9abb73b">Decoding iOS architectures</a>, where I tried to answer a simple question: How to choose the appropriate one.</p><p>In this article I’m going one level deeper into the most common (maybe not used but mentioned/documented) architectural patterns for iOS, answering these 4 questions using as example an application to list Movies:</p><ol><li>What work do the different parts do?</li><li>How do they work together?</li><li>How do they communicate with each other?</li><li>How is each piece initialized?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzewWGxQs3JsWaSAYul0nA.png" /></figure><h3>MVC</h3><p>Model — View — Controller is the foundational pattern for iOS development.</p><p>1. <strong>What work do the different parts do?</strong></p><p><strong>Model:</strong></p><ul><li>Does: Manages the application’s data and business logic. It’s the source of truth.</li><li>Doesn’t: Knows nothing about the UI.</li></ul><p><strong>View:</strong> A UIView and its subclasses.</p><ul><li>Does: Renders data onto the screen and sends user actions to the Controller.</li><li>Doesn’t: It has no deep knowledge of the data and contains no business logic. It’s owned and managed directly by the Controller.</li></ul><p><strong>Controller (`UIViewController`):</strong> This is the central hub and does most of the work.</p><ul><li>Does: It acts as the mediator between the Model and the View. It fetches data from the Model, contains the presentation logic to format that data, and then updates the View directly. It also receives actions from the View and handles all the decision-making. In many cases, it also handles navigation logic.</li><li>This is the key takeaway: The Controller’s scope is very large, leading to the common criticism of “Massive View Controller,” as it mixes business, presentation, and navigation logic.</li></ul><p>2.<strong> How do they work together? (The Controller-Driven Flow)</strong></p><p>The Controller orchestrates everything.</p><p>1. <strong>Action:</strong> A user interacts with the View (e.g., taps a button).<br> 2. <strong>Notification:</strong> The View notifies the Controller of the event using a mechanism like the Target-Action pattern or a delegate method.<br> 3. <strong>Logic &amp; Data Fetching:</strong> The Controller receives the event and processes it. It then communicates with the Model to fetch or update data.<br> 4. <strong>Model Update:</strong> The Model does its work and notifies the Controller of the result, typically via a completion handler or a Notification.<br> 5. <strong>View Update:</strong> The Controller, upon receiving the new data, directly manipulates the View and its subviews to display the result (e.g., <em>myLabel.text = …, tableView.reloadData()</em>).</p><p>3. <strong>How do they communicate with each other?</strong></p><p><strong>View -&gt; Controller:<br></strong> - Target-Action: The Controller provides a function that a <em>UIButton</em> or other control calls on an event.<br>- Delegation: The Controller acts as the delegate for the View (e.g., <em>tableView.delegate = self</em>).<br>- DataSource: A specialized delegate pattern where the Controller provides the data the View needs to render (e.g., <em>tableView.dataSource = self</em>).</p><p><strong>Controller -&gt; View:</strong><br>- Direct Reference: The Controller holds a strong, direct reference to its View (the <em>view</em> property) and can freely access and modify it and its subviews.</p><p><strong>Controller &lt;-&gt; Model:</strong><br>The Controller calls methods directly on the Model to request data. The Model should not know about the Controller. It communicates back indirectly using:<br>- NotificationCenter: The Model posts a generic notification that the Controller is listening for.<br>- Callbacks/Completion Handlers: The Controller provides a closure that the Model calls when its task is complete.</p><p>4. <strong>How is each piece initialized?</strong></p><p>In Apple&#39;s MVC, the View and Controller are very tightly coupled.</p><p><strong>Model:</strong> Usually initialized by the Controller that needs it.<br><strong>View and Controller:</strong> They are almost always created together.<br>- Via Storyboards: When a UIViewController is loaded from a Storyboard, UIKit initializes the Controller and unarchives its corresponding View hierarchy, connecting them automatically.<br>- Programmatically: You initialize the UIViewController first. The first time its view property is accessed, the Controller&#39;s loadView() method is triggered, which creates the View and its subviews in code.</p><h3>MVVM</h3><p>Model — View — ViewModel</p><p>1.<strong> What work do the different parts do?</strong></p><p><strong>Model:</strong> The layer, not the struct itself!</p><ul><li>Does: Represents the application’s data and core business logic. It defines the data structures (e.g., struct Movie) and handles communication with data sources like networks or databases via <strong>services</strong> or <strong>repositories</strong>.</li><li>Doesn’t: It has no knowledge of the UI and is completely independent of the other layers.</li></ul><p><strong>View: </strong>This can be a UIViewController or a SwiftUI View.</p><ul><li>Does: Responsible for the presentation and layout of the UI. It observes the ViewModel for state changes (when using SwiftUI or a reactive frameworks) or gets notified about changes (when using UIKit and Delegation/Closures) and displays the data it provides. It also captures user input (taps, text entry) and forwards it to the ViewModel.</li><li>Doesn’t: It contains very little logic. Its main job is to reflect the ViewModel’s state.</li></ul><p><strong>ViewModel: </strong>This is the mediator and the heart of the pattern.</p><ul><li>Does: It holds the state and presentation logic for the View. It takes raw data from the Model and transforms it into properties that the View can easily display. It exposes “commands” or methods for the View to call in response to user input.</li><li>Doesn’t: It has no direct reference to the View or its UI components. It either exposes state and lets the View react to it or notifies the UI via delegation/closures for the View to refresh with the provided data.</li></ul><p>2. <strong>How do they work together? (The State-Binding Flow)</strong></p><p>MVVM’s flow is driven by state changes and data binding.</p><p>1.<strong> Action:</strong> A user interacts with the View (e.g., types in a search bar).<br>2. <strong>Command/Binding: </strong>The View notifies the ViewModel of the change, either by calling a method (<em>viewModel.search(text:…)</em>) or through a two-way data binding that updates a property on the ViewModel (e.g., searchText).<br>3. <strong>Business Logic: </strong>The ViewModel executes its logic, then requests data from the Model layer (e.g., <em>movieService.fetchMovies(query: searchText)</em>).<br>4. <strong>State Update: </strong>The Model returns data to the ViewModel, which then updates its own state properties (e.g., <em>self.movies = […], self.isLoading = false</em>).<br>5. <strong>Observation:</strong> The View, which is observing the ViewModel’s properties, detects the change and automatically updates the UI to reflect the new state (e.g., the list of movies reloads).</p><p>3. <strong>How do they communicate with each other?</strong></p><p>Communication is primarily achieved through a pattern of observation, often called data binding.</p><p><strong>View -&gt; ViewModel:</strong><br><strong>Method Calls:</strong> The View calls functions on the ViewModel to trigger actions.<br><strong>Data Binding:</strong> The View can bind its UI elements directly to ViewModel properties (e.g., a TextField’s text is bound to a <em>searchText</em> string).</p><p><strong>ViewModel -&gt; View:</strong><br><strong>Observation / Data Binding:</strong> This is the core of MVVM. The ViewModel exposes its state as properties that the View observes. When a property’s value changes, the View is notified and updates itself.</p><p>- <strong>In SwiftUI: </strong>This is native. The ViewModel is an <em>ObservableObject</em> with <a href="http://twitter.com/Published"><em>@Published</em></a><em> </em>properties.<br>- <strong>In UIKit:</strong> This is done using Delegation, Closures/Callbacks, or a framework like Combine.</p><p><strong>ViewModel &lt;-&gt; Model:</strong><br><strong>Method Calls:</strong> The ViewModel holds a reference to the Model (or a service protocol) and calls its methods. The Model returns data via function returns (often using <em>async/await</em>).</p><p>4. <strong>How is each piece initialized?</strong></p><p>Initialization is generally simple because the View and ViewModel are more tightly coupled.</p><p><strong>Model:</strong> Services/Repositories are typically classes initialized once at app startup and injected as dependencies into the ViewModel.<br><strong>ViewModel:</strong> It is initialized with any Model-layer services it needs (dependency injection).<br><strong>View:</strong> The View is responsible for creating its own ViewModel.<br>- <strong>In SwiftUI:</strong> A View creates its ViewModel using <a href="http://twitter.com/StateObject"><em>@StateObject</em></a> (e.g., <a href="http://twitter.com/StateObject"><em>@StateObject</em></a><em> private var viewModel = MoviesViewModel()</em>).<br>- <strong>In UIKit:</strong> The <em>UIViewController</em> creates its ViewModel in its initializer or early in its lifecycle (e.g., in <em>viewDidLoad</em>).</p><h3>VIP</h3><p>View — Interactor — Presenter is a clean architecture pattern that enforces a very strict separation of concerns and a specific data flow direction.</p><p>1. <strong>What work do the different parts do?</strong></p><p>Each component has a single, well-defined responsibility.</p><p><strong>View (`UIViewController`):</strong> The View is considered “dumb”. Its only job is to display data and relay user input.</p><ul><li>Does: Owns and manages UI components (<em>UILabel</em>, <em>UITableView</em>, etc.). Captures user actions (like a button tap) and forwards the event to the Interactor.</li><li>Doesn’t: It never contains business logic or makes decisions. It simply follows display instructions from the Presenter.</li></ul><p><strong>Interactor:</strong> The Interactor is the “brains” of the scene.</p><ul><li>Does: Contains all the business logic for a specific use case (e.g., fetching the watchlist, adding an item). It receives requests from the View, communicates with the Model layer (services, workers, repositories) to get data, and performs any necessary calculations or logic.</li><li>Doesn’t: It is completely headless — it has no knowledge of the UI. It never communicates directly with the View. It works with raw data models, not formatted strings or UI elements.</li></ul><p><strong>Presenter:</strong> The Presenter is the “formatting” layer.</p><ul><li>Does: Its only job is to take raw data received from the Interactor and format it for display. For example, it turns a Date object into a “Published: Aug 14, 2025” string, or a Decimal into a “$19.99” string. It bundles this display-ready data into a simple ViewModel struct.</li><li>Doesn’t: It performs no business logic. It simply transforms data.</li></ul><p>2. <strong>How do they work together? (The Unidirectional Flow)</strong></p><p>VIP follows a strict, unidirectional data flow, often called the “VIP Cycle”.</p><p>1. <strong>Action:</strong> A user interacts with the View (e.g., taps a “Refresh” button).<br> 2. <strong>Request:</strong> The View notifies the Interactor that an event occurred, often passing a simple <em>Request</em> object (e.g., <em>interactor.fetchWatchlist()</em>).<br> 3. <strong>Business Logic:</strong> The Interactor does its work. It fetches raw data from a network or database service (the Model layer).<br> 4. <strong>Response:</strong> The Interactor passes the raw data (e.g., an array of <em>Movie</em> objects) to the Presenter inside a Response object.<br> 5. <strong>Formatting:</strong> The Presenter formats the raw data into displayable information (e.g., an array of ViewModel structs with formatted titles and release dates) and passes it to the View.<br> 6. <strong>Display:</strong> The <em>View</em> receives the <em>ViewModel</em> and updates its UI components. It performs zero logic.</p><p>This one-way flow ensures that logic is separated and the system is easy to trace and debug.</p><p>3. <strong>How do they communicate with each other?</strong></p><p>Communication is handled through a set of formal protocols that act as contracts between the components.</p><p><strong>View -&gt; Interactor:</strong> The View holds a strong reference to the Interactor (via its protocol) and calls its methods directly.<br><strong>Interactor -&gt; Presenter: </strong>The Interactor holds a strong reference to the Presenter (via its protocol) and calls its methods directly.<br><strong>Presenter -&gt; View:</strong> The Presenter holds a `weak` reference to the View (via its protocol). This <strong>weak</strong> reference is critical to prevent a retain cycle (View -&gt; Interactor -&gt; Presenter -&gt; View).</p><p>Using protocols means each component can be easily replaced with a mock for unit testing.</p><p>4. <strong>How is each piece initialized?</strong></p><p>The initialization and wiring of a scene is a key part of the VIP architecture, often handled by a Router or a dedicated Configurator object.</p><p>1. When a new scene needs to be displayed, the Owner (sometimes a Router) starts the setup process.<br>2. It initializes all the components: the <em>View</em> (e.g., <em>WatchlistViewController</em>), the <em>Interactor</em>, and the <em>Presenter</em>.<br>3. It then wires them together by setting the properties on each component:<br> — <em>view.interactor = interactor</em><br> — <em>interactor.presenter = presenter</em><br> — <em>presenter.view = view</em><br>4. This assembly process creates the complete, interconnected VIP cycle. Once wired, the Owner returns the fully configured View to be presented on screen. This setup ensures all dependencies are explicit and can be managed in one central location.</p><h3>MVVM-C (Model-View-ViewModel-Coordinator)</h3><p>MVVM-C is an extension of the MVVM pattern that adds a Coordinator to handle navigation and flow control.</p><ol><li><strong>What work do the different parts do?</strong></li></ol><p><strong>Model:</strong> Same as in MVVM, it represents the data and business logic of the application.</p><ul><li>Does: Encapsulates the data objects and business rules. Provides interfaces for data access.</li><li>Doesn’t: Has no knowledge of the UI or how data is presented.</li></ul><p><strong>View:</strong> The UI layer, similar to MVVM.</p><ul><li>Does: Renders the UI and forwards user actions to the ViewModel.</li><li>Doesn’t: Make decisions about what to display or how to respond to user input beyond simple UI state.</li></ul><p><strong>ViewModel:</strong> Still handles presentation logic and state.</p><ul><li>Does: Processes and formats data from the Model for the View. Handles UI logic and exposes commands.</li><li>Doesn’t: Handle navigation or flow between screens. This is the key difference from standard MVVM.</li></ul><p><strong>Coordinator:</strong> The new component that manages navigation flow.</p><ul><li>Does: Controls the app’s navigation and flow between screens. Creates and configures new view controllers and their dependencies.</li><li>Doesn’t: Handle business or presentation logic. It’s solely responsible for navigation decisions.</li></ul><p><strong>2. How do they work together? (The Coordinated Flow)</strong></p><p>MVVM-C adds an extra layer of abstraction for navigation control.</p><ol><li><strong>Action:</strong> A user interacts with the View (e.g., taps a movie in a list).</li><li><strong>Command:</strong> The View forwards this action to the ViewModel.</li><li><strong>Navigation Event:</strong> The ViewModel processes the action and, if navigation is needed, notifies the Coordinator (e.g., via a closure or delegate).</li><li><strong>Navigation:</strong> The Coordinator creates and configures the next screen and its dependencies, then presents it.</li><li><strong>New Screen Flow:</strong> The new screen’s View-ViewModel pair begins its own cycle of interaction with the Model.</li></ol><p><strong>3. How do they communicate with each other?</strong></p><p>Communication includes the standard MVVM patterns plus coordination events.</p><p><strong>View ↔ ViewModel:</strong> Same as in MVVM, using bindings, closures, or delegate methods.</p><p><strong>ViewModel → Coordinator:</strong></p><ul><li><strong>Delegation:</strong> The ViewModel can have a delegate protocol that the Coordinator implements.</li><li><strong>Closures:</strong> The ViewModel can expose closures that the Coordinator sets (e.g., <em>onMovieSelected: (Movie) -&gt; Void</em>).</li></ul><p><strong>Coordinator → New Views:</strong> The Coordinator creates and initializes new Views and their ViewModels, passing any required dependencies or data.</p><p><strong>4. How is each piece initialized?</strong></p><p>Initialization typically starts from the Coordinator and flows down.</p><p><strong>Coordinator:</strong> The AppDelegate or SceneDelegate creates the first (root) Coordinator. Child Coordinators are created by parent Coordinators.</p><p><strong>ViewModel:</strong> Created by the Coordinator, which injects any necessary dependencies and sets up navigation closures.</p><p><strong>View:</strong> Created by the Coordinator, which then injects the configured ViewModel.</p><p><strong>Model:</strong> Service objects are typically created once and injected through the dependency chain, or accessed via dependency injection containers.</p><p>This setup centralizes navigation logic and makes the navigation flow more testable and modular.</p><h3>VIPER</h3><p>View — Interactor — Presenter — Entity — Router is a more granular architecture that divides responsibilities into five distinct layers.</p><ol><li><strong>What work do the different parts do?</strong></li></ol><p><strong>View:</strong> Similar to other patterns, it’s the UI layer.</p><ul><li>Does: Displays what the Presenter tells it to. Captures user input and forwards it to the Presenter.</li><li>Doesn’t: Make any decisions about what to display or how to respond to user actions.</li></ul><p><strong>Interactor:</strong> Contains the business logic for a specific use case.</p><ul><li>Does: Implements business rules, fetches and manipulates data using Entities. It’s the “use case” or “business logic” layer.</li><li>Doesn’t: Format data for display or handle navigation.</li></ul><p><strong>Presenter:</strong> The coordinator between View, Interactor, and Router.</p><ul><li>Does: Takes user actions from the View, requests data from the Interactor, formats results for the View, and tells the Router when to navigate.</li><li>Doesn’t: Contain business logic or directly interact with data entities.</li></ul><p><strong>Entity:</strong> The data model objects used by the Interactor.</p><ul><li>Does: Represents the core data structures and business objects.</li><li>Doesn’t: Contain business rules or presentation logic.</li></ul><p><strong>Router:</strong> Handles navigation between modules.</p><ul><li>Does: Creates new VIPER modules and presents them. Manages navigation and passing data between modules.</li><li>Doesn’t: Contain business or presentation logic.</li></ul><p><strong>2. How do they work together? (The Module Flow)</strong></p><p>VIPER modules operate with a specific flow of information.</p><ol><li><strong>Input:</strong> The View receives user input and passes it to the Presenter.</li><li><strong>Processing Request:</strong> The Presenter decides what to do with the input and requests data or operations from the Interactor.</li><li><strong>Business Logic:</strong> The Interactor works with Entities to perform the requested operations or fetch data.</li><li><strong>Result:</strong> The Interactor returns the results to the Presenter.</li><li><strong>Formatting:</strong> The Presenter formats the data for display and tells the View what to show.</li><li><strong>Navigation:</strong> If needed, the Presenter instructs the Router to navigate to another module.</li></ol><p><strong>3. How do they communicate with each other?</strong></p><p>VIPER relies heavily on protocols to define clear interfaces between components.</p><p><strong>View → Presenter:</strong> The View holds a reference to the Presenter (via protocol) and calls methods when user actions occur.</p><p><strong>Presenter → View:</strong> The Presenter holds a weak reference to the View (via protocol) and calls methods to update the display.</p><p><strong>Presenter → Interactor:</strong> The Presenter holds a reference to the Interactor (via protocol) and calls methods to request operations.</p><p><strong>Interactor → Presenter:</strong> The Interactor typically uses delegate patterns or completion handlers to return results to the Presenter.</p><p><strong>Presenter → Router:</strong> The Presenter holds a reference to the Router (via protocol) and calls navigation methods.</p><p><strong>4. How is each piece initialized?</strong></p><p>In VIPER, modules are typically assembled by a dedicated factory or wireframe component.</p><ol><li>A Router or external component requests the creation of a new VIPER module.</li><li>The module’s wireframe (sometimes part of the Router) creates all the components: View, Presenter, Interactor, and Router.</li><li>It then connects them by setting the appropriate references:</li></ol><p>— <em>view.presenter = presenter</em></p><p>— <em>presenter.view = view</em></p><p>— <em>presenter.interactor = interactor</em></p><p>— <em>presenter.router = router</em></p><p>— <em>interactor.presenter = presenter</em></p><p>— <em>router.presenter = presenter</em></p><p>4. Any required dependencies are injected into the appropriate components.</p><p>5. The fully configured View is returned to be presented.</p><p>This modular approach makes VIPER components highly testable but requires more initial setup code.</p><h3>TCA (The Composable Architecture)</h3><p>The Composable Architecture is a modern, state-driven approach to building applications using unidirectional data flow and pure functions.</p><ol><li><strong>What work do the different parts do?</strong></li></ol><p><strong>State:</strong> The complete state of a feature or component.</p><ul><li>Does: Defines all the data needed to render a UI and track the current status of a feature.</li><li>Doesn’t: Contain any logic or behavior.</li></ul><p><strong>Action:</strong> Represents all possible events that can occur in a feature.</p><ul><li>Does: Enumerates user actions, external events, and internal state changes.</li><li>Doesn’t: Implement any behavior.</li></ul><p><strong>Reducer:</strong> Pure functions that handle state changes.</p><ul><li>Does: Takes the current state and an action, and returns a new state. Defines what effects should be executed in response to actions.</li><li>Doesn’t: Perform side effects directly or mutate state.</li></ul><p><strong>Environment:</strong> Contains all dependencies needed to run side effects.</p><ul><li>Does: Provides access to external services like API clients, analytics, etc.</li><li>Doesn’t: Contain application state or logic.</li></ul><p><strong>Store:</strong> The runtime that powers the architecture.</p><ul><li>Does: Manages state updates, dispatches actions, and executes effects. Provides a way for views to observe state.</li><li>Doesn’t: Contain feature-specific logic.</li></ul><p><strong>View:</strong> The UI layer that renders the state and sends actions.</p><ul><li>Does: Renders UI based on state. Captures user input and dispatches actions.</li><li>Doesn’t: Contain business logic or directly modify state.</li></ul><p><strong>2. How do they work together? (The Unidirectional Flow)</strong></p><p>TCA follows a strict unidirectional data flow:</p><ol><li><strong>Initial State:</strong> The Store is initialized with an initial State and a Reducer.</li><li><strong>Action:</strong> A user interacts with the View, which dispatches an Action to the Store.</li><li><strong>Reduction:</strong> The Reducer processes the Action and current State, returning a new State and any Effects to run.</li><li><strong>Effect:</strong> If an Effect was returned, the Store executes it (e.g., an API call) which may result in additional Actions being dispatched.</li><li><strong>State Update:</strong> The Store updates its State based on the Reducer’s output.</li><li><strong>View Update:</strong> The View, which is observing the Store’s State, automatically updates to reflect the new State.</li></ol><p><strong>3. How do they communicate with each other?</strong></p><p>Communication in TCA is very structured:</p><p><strong>View → Store:</strong> The View holds a reference to the Store and sends Actions through <em>store.send(action)</em>.</p><p><strong>Store → Reducer:</strong> The Store calls the Reducer with the current State and the dispatched Action.</p><p><strong>Reducer → Effects:</strong> Reducers return Effects (often created by the Environment) that the Store executes.</p><p><strong>Effects → Store:</strong> Effects complete and dispatch new Actions back to the Store.</p><p><strong>Store → View:</strong> The View observes changes to the Store’s State using <em>@ObservedObject</em> in SwiftUI or callbacks in UIKit.</p><p><strong>4. How is each piece initialized?</strong></p><p>TCA has a specific initialization flow:</p><ol><li><strong>Environment:</strong> Dependencies are created or injected from higher-level components.</li><li><strong>Initial State:</strong> The initial State for a feature is defined, often with default values.</li><li><strong>Reducer:</strong> The Reducer function is defined, often composed of smaller, more focused reducers.</li><li><strong>Store:</strong> A Store is created with the initial State, Reducer, and Environment.</li><li><strong>View:</strong> The View is initialized with the Store, allowing it to observe State and dispatch Actions.</li></ol><p>TCA is particularly well-suited for SwiftUI but can be adapted for UIKit. Its key advantages are composability (combining smaller features into larger ones), testability, and a consistent approach to side effects.</p><h3>Conclusion</h3><p>Each architectural pattern has its strengths and ideal use cases:</p><ul><li><strong>MVC</strong> is simple and quick to implement but can lead to massive view controllers in complex apps.</li><li><strong>MVVM</strong> provides better separation of concerns and testability while remaining relatively intuitive.</li><li><strong>MVVM-C</strong> adds navigation management to MVVM, making it ideal for apps with complex flows.</li><li><strong>VIP</strong> enforces a strict unidirectional flow that makes data paths clear and debugging easier.</li><li><strong>VIPER</strong> offers maximum separation of concerns for large, complex applications with many developers.</li><li><strong>TCA</strong> provides a functional approach with excellent state management and composability, particularly well-suited for SwiftUI apps.</li></ul><p>The best architecture for your project depends on factors like team size, project complexity, and familiarity with the patterns. Many successful apps use hybrid approaches, applying different patterns to different parts of the application based on specific needs.</p><p>Remember that architectural patterns are tools to help manage complexity, not dogmatic rules. The goal is always to create maintainable, testable code that can evolve with changing requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b72a4f5e6fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding iOS Architectures]]></title>
            <link>https://medium.com/@jaiversin/decoding-ios-architectures-f9bec9abb73b?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bec9abb73b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mobile-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[architectural-patterns]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 17:03:05 GMT</pubDate>
            <atom:updated>2025-07-21T23:34:17.558Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why Architecture Matters More Than Ever</strong></h3><p>In modern iOS development, architecture is more than structure — it’s a blueprint for team collaboration, testability, feature velocity, and ultimately, code quality. Yet, many discussions around patterns devolve into dogma. Should we go full VIPER or just keep things lean with MVVM? Is Clean Architecture overkill for a small team? This article walks through common iOS architecture patterns, their trade-offs, and a framework to help you decide which one fits your use case best — especially in technical interviews and architectural debates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCRYf9w0ECuPef6yNYK_SQ.png" /><figcaption>Decoding iOS Architectures</figcaption></figure><p><strong>Patterns We’ll Cover</strong></p><p>- MVC (Model-View-Controller)<br>- MVVM (Model-View-ViewModel)<br>- VM-Only (Lightweight ViewModel-based architectures)<br>- VIP (View-Interactor-Presenter)<br>- VIPER (VIP + Entity + Router)<br>- Clean Architecture<br>- Modular &amp; Composable approaches (e.g., TCA, RIBs)</p><h3><strong>Architecture Deep Dive</strong></h3><ol><li><a href="https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html"><strong>MVC</strong></a></li></ol><p><strong>Core idea:</strong> Apple’s default architecture. View and Controller tightly coupled.</p><p><strong>Pros</strong>:</p><ul><li>Simple to start with.</li><li>Supported by Interface Builder and Xcode templates.</li></ul><p><strong>Cons</strong>:</p><ul><li>“Massive View Controller” problem.</li><li>Difficult to scale with a team.</li></ul><p><strong>Example Structure:</strong></p><pre>├── ViewControllers/<br>│   └── LoginViewController.swift<br>├── Models/<br>│   └── User.swift<br>└── Views/<br>    └── LoginView.swift</pre><p><strong>2. </strong><a href="https://www.kodeco.com/34-design-patterns-by-tutorials-mvvm"><strong>MVVM</strong></a></p><p><strong>Core idea:</strong> ViewModel sits between View and Model, providing binding and state transformations.</p><p><strong>Pros</strong>:</p><ul><li>Testable ViewModel logic.</li><li>Works well with SwiftUI.</li><li>Clean data binding if used with Combine or RxSwift.</li></ul><p><strong>Cons</strong>:</p><ul><li>ViewModels can become bloated.</li><li>Binding complexity increases with feature depth.</li></ul><p><strong>Example Structure:</strong></p><pre>├── Views/<br>│   └── LoginView.swift<br>├── ViewModels/<br>│   └── LoginViewModel.swift<br>└── Models/<br>    └── User.swift</pre><p><strong>3. </strong><a href="https://medium.com/better-programming/swiftui-architecture-a-complete-guide-to-mv-pattern-approach-5f411eaaaf9e"><strong>ViewModel-Only</strong></a><strong> (Lean MVVM)</strong></p><p><strong>Core idea:</strong> A pragmatic take on MVVM, <a href="https://azamsharp.com/2022/07/21/view-is-the-view-model.html">skipping formal separation where unnecessary</a>.</p><p><strong>Pros</strong>:</p><ul><li>Minimal boilerplate.</li><li>Easy onboarding for small teams.</li></ul><p><strong>Cons</strong>:</p><ul><li>Risk of unclear boundaries.</li><li>Can turn into disguised MVC.</li></ul><p><strong>Example Structure:</strong></p><pre>├── Screens/<br>│   └── LoginScreen.swift<br>└── ViewModels/<br>    └── LoginViewModel.swift</pre><p><strong>4. </strong><a href="https://www.kodeco.com/29416318-getting-started-with-the-vip-clean-architecture-pattern/page/3"><strong>VIP</strong></a></p><p><strong>Core idea:</strong> Apple-inspired Clean pattern with strict roles: View (ViewController), Interactor, Presenter.</p><p><strong>Pros</strong>:</p><ul><li>Clear separation of concerns.</li><li>Great for testability and team scalability.</li></ul><p><strong>Cons</strong>:</p><ul><li>Boilerplate overhead.</li><li>May feel rigid for simple flows.</li></ul><p><strong>Example Structure:</strong></p><pre>├── Login/<br>│   ├── LoginViewController.swift<br>│   ├── LoginInteractor.swift<br>│   ├── LoginPresenter.swift<br>│   ├── LoginWorker.swift<br>│   └── LoginModels.swift</pre><p><strong>5. </strong><a href="https://www.kodeco.com/8440907-getting-started-with-the-viper-architecture-pattern"><strong>VIPER</strong></a></p><p><strong>Core idea:</strong> Adds Routing and Entities to VIP, creating a five-layered structure.</p><p><strong>Pros</strong>:</p><ul><li>Explicitly defines responsibility.</li><li>Encourages modularization.</li></ul><p><strong>Cons</strong>:</p><ul><li>Verbose setup.</li><li>Onboarding cost for new team members.</li></ul><p><strong>Example Structure:</strong></p><pre>├── Login/<br>│   ├── LoginView.swift<br>│   ├── LoginInteractor.swift<br>│   ├── LoginPresenter.swift<br>│   ├── LoginEntity.swift<br>│   └── LoginRouter.swift</pre><p><strong>6. </strong><a href="https://blog.cleancoder.com/uncle-bob/2011/11/22/Clean-Architecture.html"><strong>Clean Architecture</strong></a></p><p><strong>Core idea:</strong> Domain-driven, use-case-centric structure with dependency inversion.</p><p><strong>Pros</strong>:</p><ul><li>Strong boundaries between UI and business logic.</li><li>Promotes reuse and testability.</li></ul><p><strong>Cons</strong>:</p><ul><li>High complexity.</li><li>Overhead in smaller or fast-moving projects.</li></ul><p><strong>Example Structure</strong>:</p><pre>├── Presentation/<br>│   └── LoginViewController.swift<br>├── Domain/<br>│   ├── Entities/<br>│   │   └── User.swift<br>│   └── UseCases/<br>│       └── LoginUser.swift<br>└── Data/<br>    └── Repositories/<br>        └── UserRepository.swift</pre><p><strong>7. Composable Architectures (</strong><a href="https://github.com/pointfreeco/swift-composable-architecture"><strong>TCA</strong></a><strong>, </strong><a href="https://github.com/uber/RIBs"><strong>RIBs</strong></a><strong>)</strong></p><p><strong>Core idea</strong>: Declarative and modular, with single source of truth and reducers.</p><p><strong>Pros</strong>:</p><ul><li>Scalable across teams.</li><li>Embraces unidirectional data flow.</li></ul><p><strong>Cons</strong>:</p><ul><li>Steep learning curve.</li><li>Boilerplate and dependency on frameworks.</li></ul><p><strong>Example Structure (TCA)</strong>:</p><pre>├── Features/<br>│   └── Login/<br>│       ├── LoginView.swift<br>│       ├── LoginReducer.swift<br>│       └── LoginEnvironment.swift<br>└── AppStore.swift</pre><h3>Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJwlg-CpQ9DRwirUZ430vQ.png" /></figure><h3>How to Choose the Right Pattern</h3><p>Ask yourself:</p><p><strong>What is your team size and expertise?</strong></p><ul><li>If you have a <strong>small team</strong> with <strong>limited experience</strong>, favor lighter patterns like <strong>MVVM</strong> or <strong>VM</strong>-<strong>only</strong>. These are easier to onboard and refactor later.</li><li><strong>Larger teams</strong> benefit from stricter boundaries like <strong>VIP</strong>, <strong>VIPER</strong>, or <strong>Clean Architecture </strong>to avoid merge conflicts and promote parallel development.</li></ul><p><strong>Is the app domain-driven or UI-heavy?</strong></p><p>A <strong>domain-driven app</strong> has complex business rules, multiple data sources, and focuses more on behavior than presentation. Examples: e-commerce apps, finance tools, health tech.</p><p>➤ Recommended: <strong>Clean Architecture</strong>, <strong>VIPER</strong>, or <strong>Composable (TCA) </strong>to isolate core logic from UI.</p><p>A <strong>UI-heavy app</strong> centers around fluid navigation, animations, and visual elements, often with minimal business logic. Examples: media players, design tools, lifestyle apps.</p><p>➤ Recommended: <strong>MVVM</strong>, <strong>VM-only</strong>, or even <strong>MVC </strong>for fast iteration and simple flows.</p><p><strong>What’s the lifetime of the app?</strong></p><p>If it’s a short-lived MVP or marketing experiment, go lean. Avoid overengineering.</p><p>➤ Use: <strong>MVC</strong> or <strong>VM-only</strong>.</p><p>If the app will evolve for years with new features and a large team:</p><p>➤ Use: <strong>Clean Architecture</strong>, <strong>VIPER</strong>, or <strong>TCA</strong>.</p><p><strong>How much do you value testability vs. speed of iteration?</strong></p><ul><li>Favor <strong>testable patterns</strong> like <strong>VIP</strong>, <strong>Clean</strong>, or <strong>Composable</strong> when quality, regulation, or scale matters.</li><li>Prefer <strong>speed-optimized patterns</strong> like <strong>MVVM</strong> or <strong>VM-only</strong> for early-stage product development.</li></ul><p><strong>Do you expect frequent onboarding of new developers?</strong></p><ul><li>If yes, use architectures with clear folder structure and file roles (e.g., <strong>VIP</strong>, <strong>MVVM</strong>). Consider documentation or code generation tools.</li><li>If no, and you have a stable senior team, a hybrid or more pragmatic architecture can evolve organically.</li></ul><h3>Final Thoughts</h3><p>At the end of the day, your architecture should answer one question: does every developer on your team know where their code should go?</p><p>Clean and Composable architectures are fantastic when you have the time and discipline to apply them correctly. MVVM and VIP offer a sweet spot for clarity without heavy ceremony. And even patterns like MVC or ViewModel-only can shine in small, focused projects.</p><p>Don’t get caught chasing the latest trend or overengineering a solution. Choose the architecture that helps your team ship confidently, onboard quickly, and scale without fear.</p><p>And if in doubt? Start simple. You can always modularize later — refactoring is easier than untangling a bloated mess you didn’t need in the first place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bec9abb73b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ser mando medio en tech: mucho conocimiento, poco poder]]></title>
            <link>https://medium.com/@jaiversin/ser-mando-medio-en-tech-mucho-conocimiento-poco-poder-9745580b53e1?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/9745580b53e1</guid>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[technical-leadership]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 22:34:55 GMT</pubDate>
            <atom:updated>2025-06-13T22:34:55.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Después de más de 15 años en la industria del software (un poco más, pero no vamos a revelar qué tan viejo estoy), pasando por roles técnicos, de liderazgo y gestión, puedo decir con un buen nivel de confianza que hay un rol especialmente incómodo en la escalera corporativa: el mando medio.</p><p>No es un mal lugar. Tampoco es el más cómodo. Es más bien una especie de punto de cruce entre lo técnico y lo estratégico, entre las personas y los procesos, entre lo que se dice y lo que realmente pasa.</p><p>Aquí algunas verdades que he aprendido desde esta trinchera intermedia.</p><h3>1. Sabes mucho, decides poco</h3><p>Con los años acumulas conocimiento. Sabes cómo funciona el negocio, qué necesita el equipo, cómo se rompen las cosas y, con suerte, cómo se arreglan. Tienes una vista panorámica: lo técnico, lo humano, lo organizacional.</p><p>Pero esa claridad no siempre viene con poder de decisión. A veces, estás ahí para traducir estrategias, no para definirlas. Para aplicar ideas que ya llegan cocinadas, aunque tú sepas que por dentro están crudas.</p><h3>2. Empatizas con todos, pero no representas a nadie</h3><p>Estás cerca del equipo, conoces sus dolores, sus expectativas, sus memes internos. También hablas seguido con management y entiendes por qué se toman ciertas decisiones desde el negocio.</p><p>Ese equilibrio te deja en un terreno extraño: ni eres “uno de ellos” ni eres “uno de los otros”. Eres el que tiene que explicar a cada lado lo que pasa del otro, mientras cargas con la mirada de sospecha de ambos.</p><h3>3. Pones la cara, incluso cuando no es tuya la película</h3><p>Una parte inevitable del rol es ser el portavoz de decisiones que no se originaron en tu equipo. Explicar cambios, reorganizaciones o prioridades nuevas que llegan sin mucho contexto. Tratar de generar confianza mientras tú mismo estás buscando respuestas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxMc8gyruPtiEuF1rzfuHg.png" /></figure><p>No es un drama, pero sí es una coreografía complicada: mantener al equipo enfocado y motivado, sin convertirte en un robot corporativo ni en un vocero de la frustración.</p><h3>4. Liderar con lo que hay (y lo que no)</h3><p>Hay momentos en que no tienes herramientas tradicionales para motivar: aumentos, promociones, beneficios concretos. Entonces trabajás con lo intangible. Clima. Cercanía. Transparencia. Sentido de equipo.</p><p>Y a veces, eso alcanza. Otras, simplemente no. No porque falte voluntad, sino porque hay factores que no puedes controlar. Lo importante es entender los límites sin perder el foco en las personas. Pero eso tiene fecha de vencimiento. El desgaste llega. Y cuando no hay más que ofrecer, los lazos afectivos no alcanzan para retener talento. Y lo sabes. Y te duele.</p><h3>5. Decidir el camino: técnico o gestión</h3><p>Una decisión que no muchos comentan, pero que se vuelve central en este punto, es qué camino seguir. ¿Te vuelcas completamente a la gestión y dejas atrás la práctica técnica? ¿Buscas un híbrido? ¿Te reinventas?</p><p>El problema es que no sabes si elegiste bien hasta que llega el siguiente gran cambio: una reestructura, una nueva oportunidad, o una oferta externa que te obliga a mirar todo desde cero. No hay un GPS. Solo aprendizaje continuo y algo de intuición.</p><h3>Conclusión: bienvenidos a la montaña rusa</h3><p>Ser mando medio en tech es como estar en el asiento del medio en un paseo en bus: no manejas, pero escuchas al conductor y también a los que vienen atrás quejándose del camino. Tienes que pasar el mensaje, calmar los ánimos, y de vez en cuando, repartir snacks imaginarios para que nadie se quiera bajar en la próxima parada.</p><p>¿Es difícil? Sí.<br> ¿Es enriquecedor? También.<br> ¿Es confuso? Casi siempre.<br> ¿Lo volvería a hacer? No te sabría decir… pregúntame en el próximo one-on-one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9745580b53e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Tricks — Codable Dinámico]]></title>
            <link>https://medium.com/@jaiversin/swift-tricks-codable-din%C3%A1mico-fad75af9a44e?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad75af9a44e</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[codable]]></category>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Mon, 12 May 2025 05:50:36 GMT</pubDate>
            <atom:updated>2025-05-13T03:31:42.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift Tricks — Codable Dinámico</h3><p>Aunque Codable es un tópico bastante conocido y documentado (no por Apple por supuesto), hay ciertas ocasiones en las que las respuestas de los servicios no son ideales y nos obligan a indagar un poco más para encontrar soluciones creativas. En este caso, presento un par de opciones de solución para un problema, más cercano a la duplicación de código que a Codable en sí.</p><p>Nota: Este artículo no cubre manejo de errores al decodificar, lo cual puede ser muy útil a la hora de encontrar problemas con llaves faltantes o contenido corrupto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq81fS-08hMgid_nDZM4Yw.png" /><figcaption>Sí, AI generated :)</figcaption></figure><p>Mientras hacía una aplicación en la que tengo que presentar varias listas de diferentes modelos (Cafés, Tiendas de Café, Tostadores), y que a su vez, todos pueden ser “paginables” (soñando que mi aplicación sea un éxito y tenga miles de resultados qué mostrar), me encontré con el reto de cómo decodificar las respuestas, sin repetir mucho código.</p><p>Para hacerse a una idea, estos son ejemplos de cómo se ven las respuestas de un llamado a un API que retorna los modelos con información de paginación:</p><pre>{<br>    &quot;coffees&quot;: [<br>        {<br>            &quot;roaster&quot;: {<br>                &quot;name&quot;: &quot;New Roaster&quot;,<br>                &quot;location&quot;: &quot;City&quot;,<br>                &quot;id&quot;: &quot;6817c9c4c5b342da74c3c6d7&quot;<br>            },<br>            &quot;name&quot;: &quot;New Coffee&quot;,<br>            &quot;origin&quot;: &quot;Colombia&quot;,<br>            &quot;roastLevel&quot;: &quot;light&quot;,<br>            &quot;price&quot;: 20,<br>            &quot;availableQuantity&quot;: 0,<br>        }<br>    ],<br>    &quot;total&quot;: 1,<br>    &quot;page&quot;: 1,<br>    &quot;totalPages&quot;: 1<br>}</pre><pre>{<br>    &quot;roasters&quot;: [<br>        {<br>          &quot;contact&quot;: {<br>                &quot;phone&quot;: &quot;2061234567&quot;,<br>                &quot;email&quot;: &quot;roaster@example.com&quot;<br>            },<br>            &quot;name&quot;: &quot;New Roaster&quot;<br>        }<br>    ],<br>    &quot;total&quot;: 1,<br>    &quot;page&quot;: 1,<br>    &quot;totalPages&quot;: 1<br>}</pre><pre>{<br>    &quot;shops&quot;: [<br>        {<br>            &quot;contact&quot;: {<br>                &quot;phone&quot;: &quot;2061234567&quot;,<br>                &quot;email&quot;: &quot;shop@example.com&quot;<br>            },<br>            &quot;name&quot;: &quot;New Shop&quot;,<br>            &quot;user&quot;: {<br>                &quot;email&quot;: &quot;user@example.com&quot;,<br>                &quot;name&quot;: &quot;User&quot;<br>            },<br>            &quot;location&quot;: &quot;City&quot;,<br>        }<br>    ],<br>    &quot;total&quot;: 1,<br>    &quot;page&quot;: 1,<br>    &quot;totalPages&quot;: 1<br>}</pre><p>La intención es no tener que crear modelos con propiedades casi idénticas que contengan los resultados del llamado a los APIs con información de paginación.</p><h3>Primera Alternativa — Protocolo Pageable + Wrapper</h3><p>Mi primer acercamiento fue crear un protocolo <em>Pageable</em> con las propiedades de paginación (page, totalPages, total) y agregar manualmente un wrapper a cada modelo, algo como CoffeesPaging y RoastersPaging, que conformara al protocolo y agregara una propiedad con el arreglo de modelos correspondientes (coffees o roasters).</p><pre>// 1. Protocolo con las propiedades comunes entre los APIs<br>protocol Pageable: Decodable {<br>    var total: Int { get }<br>    var page: Int { get }<br>    var totalPages: Int { get }<br>}<br><br>// 2. Wrapper del modelo Coffee<br>struct CoffeesPaging: Decodable, Pageable {<br>    let coffees: [Coffee]<br>    let total: Int<br>    let page: Int<br>    let totalPages: Int<br>}<br>---------------------------<br><br>APIClient.request(...)<br>...<br>.sink(receiveCompletion: { [weak self] completion in<br>    self?.isLoading = false<br>    if case let .failure(error) = completion {<br>        self?.errorMessage = error.localizedDescription<br>    }<br>// 3. Referencia explícita al Wrapper<br>}, receiveValue: { [weak self] (coffeesPaging: CoffeePaging) in <br>    // 4. Accediendo a la propiedad del wrapper con el arreglo de items<br>    self?.coffees = coffeesPaging.coffees<br>})</pre><ol><li>Protocolo Pageable</li><li>Wrapper para cada modelo con una propiedad para contener los items (un arreglo). Cada wrapper tiene una propiedad y su nombre es el plural del modelo (<em>coffees</em> en el caso de <em>CoffeesPaging</em>)</li><li>Agregar el tipo explícito del Wrapper al recibir la data para que se pueda inferir el tipo al momento de decodificar</li><li>Acceder a la propiedad con el arreglo de items y asignarla a la propiedad publicada para refrescar la UI</li></ol><h3>Segunda Alternativa — AnyCodable</h3><p>Para esta alternativa, hago uso de una librería del gran <a href="https://github.com/mattt">Mattt</a>, llamada <a href="https://github.com/Flight-School/AnyCodable">AnyCodable</a>, que permite decodificar JSON sin una estructura definida (sin modelos específicos) a un diccionario (llave-valor) de múltiples niveles. Para este ejemplo, voy a omitir los pasos para instalar la librería, pero están bastante claros y sencillos <a href="https://github.com/Flight-School/AnyCodable/blob/master/README.md">aquí</a>.</p><pre>// 1. Modelo con las propiedades comunes entre los APIs<br>struct DynamicResponse: Decodable {<br>    // 2. Propiedad para contener el arreglo de objetos<br>    let data: [String: AnyCodable]<br>    let total: Int<br>    let page: Int<br>    let totalPages: Int<br><br>    // 3. Keys &quot;estáticas&quot; o que siempre tiene el JSON (total, page, totalPages)<br>    enum CodingKeys: String, CodingKey {<br>        case total, page, totalPages<br>    }<br><br>    init(from decoder: Decoder) throws {<br>        // 4. Decodificando las keys estáticas<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        total = try container.decode(Int.self, forKey: .total)<br>        page = try container.decode(Int.self, forKey: .page)<br>        totalPages = try container.decode(Int.self, forKey: .totalPages)<br><br>        // 5. Creando el contenedor usando la definición para una llave dinámica<br>        let dynamicContainer = try decoder.container(keyedBy: DynamicKey.self)<br>        var tempData: [String: AnyCodable] = [:]<br>        for key in dynamicContainer.allKeys {<br>            // 6. Decodificando la propiedad dinámica que contiene el arreglo de objetos <br>            // usando AnyCodable en lugar de una estructura definida (un modelo) <br>            tempData[key.stringValue] = try dynamicContainer.decode(AnyCodable.self, forKey: key)<br>        }<br>        data = tempData<br>    }<br>}<br><br>// 7. Definición de la estructura para el CodingKey dinámico<br>struct DynamicKey: CodingKey {<br>    var stringValue: String<br>    var intValue: Int?<br><br>    init?(stringValue: String) {<br>        self.stringValue = stringValue<br>    }<br><br>    init?(intValue: Int) {<br>        return nil<br>    }<br>}<br><br>--------------------<br><br>APIClient.request(...)<br>...<br>.sink(receiveCompletion: { [weak self] completion in<br>    self?.isLoading = false<br>    if case let .failure(error) = completion {<br>        self?.errorMessage = error.localizedDescription<br>    }<br>   // 8. Referencia a la estructura con la propiedad dinámica DynamicResponse<br>}, receiveValue: { [weak self] (coffeesResult: DynamicResponse) in<br>    var coffeesResultArray: [Coffee] = []<br>    // 9. Accedo via subscript a la propiedad coffeesResult.data[&quot;coffees&quot;]<br>    // Lo hago directamente acá para no extender mucho el ejemplo, <br>    // pero hay mejores formas de hacer esto :)<br>    if let coffees = coffeesResult.data[&quot;coffees&quot;]?.value as? [[String: Any]] {<br>        for coffee in coffees {<br>            let roaster = coffee[&quot;roaster&quot;] as? [String: Any]<br>            coffeesResultArray.append(Coffee(id: coffee[&quot;_id&quot;] as? String ?? &quot;&quot;,<br>                               name: coffee[&quot;name&quot;] as? String ?? &quot;&quot;,<br>                               roaster: Roaster(id: roaster?[&quot;_id&quot;] as? String ?? &quot;&quot;,<br>                                                name: roaster?[&quot;name&quot;] as? String ?? &quot;&quot;,<br>                                                location: roaster?[&quot;location&quot;] as? String ?? &quot;&quot;),<br>                               origin: coffee[&quot;origin&quot;] as? String ?? &quot;&quot;,<br>                               roastLevel: coffee[&quot;roastLevel&quot;] as? String ?? &quot;&quot;,<br>                               description: coffee[&quot;description&quot;] as? String ?? &quot;&quot;,<br>                               price: coffee[&quot;price&quot;] as? Double ?? 0.0,<br>                               availableQuantity: coffee[&quot;availableQuantity&quot;] as? Int ?? 0))<br>        }<br>    }<br><br>    self?.result.entries = coffeesResultArray<br>})</pre><ol><li>Modelo con las propiedades comunes entre los APIs</li><li>Propiedad que va a contener los objetos</li><li>Enum CodingKeys con los keys de las propiedades compartidas, es decir (total, page, totalPages)</li><li>Se decodifican estas propiedades primero</li><li>Se crea el contenedor con referencia a la estructura de clave dinámica DynamicKey</li><li>Se decodifica la propiedad dinámica que contiene el arreglo de objetos usando AnyCodable en lugar de una estructura definida (un modelo)</li><li>Estructura DynamicKey para el CodingKey dinámico</li><li>Referencia a la estructura con la propiedad dinámica DynamicResponse, para poder inferir el tipo en el decoding</li><li>Creación de los modelos, porque en definitiva, las vistas esperan estructuras para poder pintar la data</li></ol><p>Esta alternativa, aunque es bastante dinámica, requiere crear estructuras a partir de un diccionario. Y aunque esto en el ejemplo, podría hacerse de una mejor manera, aún habría que replicarlo en cada uno de los modelos.</p><h3>Tercera Alternativa — Protocolo + Generics + Custom Decoding</h3><pre>// 1. Protocolo con las propiedades comunes entre los APIs<br>protocol Pageable: Decodable {<br>    var total: Int { get }<br>    var page: Int { get }<br>    var totalPages: Int { get }<br>}<br><br>// 2. Estructura genérica y &quot;paginable&quot;<br>struct PageableResult&lt;T: Decodable&gt;: Pageable {<br>    var total: Int<br>    var page: Int<br>    var totalPages: Int<br>    var entries: [T] // 3. Propiedad para contener los modelos<br><br>    // 4. Keys &quot;estáticas&quot; o que siempre tiene el JSON (total, page, totalPages) <br>    // y keys &quot;dinámicas&quot; o que posiblemente tiene (coffees, roasters, shops) <br>    // dependiendo del listado que estamos consumiendo<br>    enum CodingKeys: String, CodingKey {<br>        case total, page, totalPages, coffees, roasters, shops<br>    }<br><br>    init(from decoder: Decoder) throws {<br>        // 5. Decodificando las propiedades &quot;estáticas&quot;<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        total = try container.decode(Int.self, forKey: .total)<br>        page = try container.decode(Int.self, forKey: .page)<br>        totalPages = try container.decode(Int.self, forKey: .totalPages)<br>        <br>        // 6. Decodificando la propiedad &quot;dinámica&quot; y asignándola a entries<br>        switch T.self {<br>        case is Coffee.Type:<br>            entries = try container.decode([T].self, forKey: CodingKeys.coffees)<br>        case is Roaster.Type:<br>            entries = try container.decode([T].self, forKey: CodingKeys.roasters)<br>        case is Shop.Type:<br>            entries = try container.decode([T].self, forKey: CodingKeys.shops)<br>        default:<br>            // Valor por defecto si se proporciona un modelo de un tipo no soportado<br>            entries = []<br>        }<br>    }<br>}<br><br>--------------------<br><br>APIClient.request(...)<br>...<br>.sink(receiveCompletion: { [weak self] completion in<br>    self?.isLoading = false<br>    if case let .failure(error) = completion {<br>        self?.errorMessage = error.localizedDescription<br>    }<br>   // 7. Ya no hago referencia al wrapper sino a mi estructura <br>   // genérica PageableResult<br>}, receiveValue: { [weak self] (result: PageableResult&lt;Coffee&gt;) in <br>    // 8. La asignación siempre se hace con la propiedad entries<br>    self?.coffees = result.entries<br>})</pre><ol><li>Decidí mantener el protocolo Pageable por claridad</li><li>Estructura genérica <em>PageableResult&lt;T: Decodable&gt; </em>para los modelos como Coffee y Roaster, que son Decodable</li><li>Propiedad para contener los modelos (un arreglo), en este caso llamada <em>entries</em>, que va a ser usada para la asignación en donde se llame al APIClient</li><li>Enum CodingKeys con todos los posibles keys del JSON a decodificar. Algo interesante que notar es que este enum puede contener keys para propiedades que no están definidas en la estructura pero sí pueden existir en el JSON</li><li>Custom Decoding utilizando directamente las CodingKeys para las propiedades del protocolo Pageable (total, page, totalPages)</li><li>Decoding dinámico, basado en el tipo del valor genérico <em>T.self</em></li><li>Referencia explícita a la nueva estructura genérica <em>PageableResult</em></li><li>Asignación de la lista de resultados usando la propiedad <em>entries</em></li></ol><p>Con esta solución, no tengo que crear wrappers para cada modelo pero tengo que modificar un poco la forma en que recibo la respuesta con algo más genérico.</p><h3>Conclusión</h3><p>Codable es una herramienta bastante útil y sencilla de implementar cuando tenemos respuestas de servicios ideales… Si no es así, una combinación de otras herramientas (como AnyCodable y Generics) y algo un poco menos “común” de Codable, puede hacer una gran diferencia en legibilidad, mantenibilidad y sencillez del código.</p><h4>Referencias</h4><p>Artículos que hablan de este tópico:</p><p><a href="https://matteomanferdini.com/swift-codable-dynamic-type/">https://matteomanferdini.com/swift-codable-dynamic-type/</a></p><p><a href="https://www.swiftbysundell.com/articles/handling-model-variants-in-swift/">Handling model variants in Swift | Swift by Sundell</a></p><p><a href="https://forums.swift.org/t/codable-dynamic-types/62333/3">https://forums.swift.org/t/codable-dynamic-types/62333/3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad75af9a44e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arquitectura de aplicaciones móviles]]></title>
            <link>https://medium.com/@jaiversin/arquitectura-de-aplicaciones-m%C3%B3viles-4fddfd6e85a1?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fddfd6e85a1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[arquitectura-de-software]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aplicaciones-móviles]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 04:33:29 GMT</pubDate>
            <atom:updated>2024-10-01T04:33:29.382Z</atom:updated>
            <content:encoded><![CDATA[<p>En los últimos meses, me he dado a la tarea de definir lo que, para mí, sería una arquitectura de referencia para construir aplicaciones móviles. Este artículo se centra en una arquitectura específica para aplicaciones iOS, desarrolladas con Swift y SwiftUI.</p><p>La arquitectura o más específicamente las decisiones arquitectónicas, se apoyan en factores determinantes de arquitectura, conocidos también como drivers.</p><p>Estos factores pueden estar definidos como:</p><ul><li><strong>Requisitos funcionales:</strong> lo que la aplicación debe hacer.</li><li><strong>Requisitos no funcionales:</strong> cómo la aplicación debe comportarse en términos de rendimiento, seguridad, usabilidad, escalabilidad, entre otros.</li><li><strong>Restricciones o limitaciones: </strong>como lenguajes, tecnologías, presupuesto, tiempo, infraestructura existente, políticas organizacionales, por mencionar algunos.</li></ul><p>A lo largo de este artículo, exploraré cómo estos factores influyen en la definición de una arquitectura robusta y escalable para aplicaciones móviles iOS.</p><h3>Estructura de archivos</h3><p>Cuando comencé a desarrollar la primera versión de mi aplicación de prueba, me enfrenté a la primera pregunta fundamental: ¿Cómo organizar el código de manera que sea fácil de entender, con una clara definición de límites y sin clases con responsabilidades múltiples (o clases manager que no encajan en ninguna parte)?</p><p>Mi primera aproximación fue usar las capas definidas por Clean Architecture (Dominio, Presentación, Datos o Persistencia) con un enfoque de Diseño Guiado por el Dominio (o DDD Domain Driven Design).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*kX1cbLTzIRvQEFF1FRarHw.png" /></figure><p>Usar una arquitectura bien conocida como guía para la ubicación de los archivos es útil, ya que ayuda a los desarrolladores a respetar sus principios, límites y las restricciones que propone.</p><p>Sin embargo, esta organización puede limitar la modularización de la aplicación a módulos por capas (modularización horizontal) y excluyendo la modularización por funcionalidades o características (modularización vertical). En mi caso, dado que las primeras versiones de la aplicación serán desarrolladas y mantenidas por una sola persona (yo), opté por la modularización horizontal.</p><p>Si se tratara de una aplicación construida y mantenida por un grupo de personas, en la que la <em>escalabilidad</em>, la división de la aplicación por verticales y la apropiación de éstas (ownership) tuviera más peso, la modularización vertical sería más adecuada.</p><h3>Capa de presentación</h3><p>Para definir la capa de presentación, opté por una combinación de MVVM y Router debido a restricciones tecnológicas (definidas por mi) y a mi interés en aprender más sobre SwiftUI.</p><p>Aunque el uso de View Models puede ser “opcional” en SwiftUI, personalmente creo que ayudan a separar responsabilidades y a clarificar dónde debe realizarse la comunicación con los casos de uso o interactores (el término que decidí usar basado en otros patrones arquitectónicos).</p><p>Hasta cierto punto, al usar un Router y nombrar Interactors a mis Casos de Uso, hay una similitud con el patrón VIPER, pero lo dejaré a criterio del lector.</p><figure><img alt="Presentatio Layer — Capa de Presentación" src="https://cdn-images-1.medium.com/max/734/1*pLc4Qgos2jGF_AhU9IkD0A.png" /></figure><p>Otra decisión importante fue utilizar <a href="https://blog.jacobstechtavern.com/p/swiftui-apps-at-scale">UIKit para el manejo de la navegación </a>dentro de los Routers en lugar de las APIs nativas de SwiftUI. El <em>driver</em> de esta decisión fue la mantenibilidad. Existen artículos y opiniones comunes de que SwiftUI, en las versiones que utilicé, no estaba completamente preparado para manejar aplicaciones medianas o grandes que requieren navegación compleja y animaciones personalizadas. Esto podría generar problemas en el futuro, por lo que decidí usar UIKit para garantizar una mayor estabilidad y flexibilidad.</p><h3>Capa de Dominio</h3><p>La capa de dominio se puede dividir en dos sub-secciones: una sección “estática” que contiene la definición de las entidades o los objetos de negocio, y una sección “dinámica” que contiene los casos de uso (interactores) que manipulan esas entidades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*B5CVilxcUteEceBE8NKBpQ.png" /></figure><p>Para adherirse a los principios de Clean Architecture, los casos de uso se representan como protocolos y se implementan como casos de uso por defecto (DefaultInteractor). Esta estructura permite que los interactores sean fácilmente mockeados o simulados para pruebas unitarias, pruebas de UI o simplemente para ser usados en los SwiftUI Previews.</p><p>Las implementaciones de los Casos de Uso tienen lógica específica para la funcionalidad que cubren e interactúan con Entidades para dar respuesta a sus consumidores, como los View Model.</p><p>La capa de dominio depende indirectamente de los repositorios de información que mantienen o proporcionan instancias de las entidades. Para lograr esta dependencia indirecta, la capa de dominio define protocolos o interfaces que los Repositorios (ubicados en la capa de datos/persistencia) deben implementar. Esto es un ejemplo de inversión de dependencia y el patrón de diseño Repository.</p><h3><strong>Capa de Datos/Persistencia</strong></h3><p>Los repositorios en esta capa implementan los protocolos definidos en la capa de dominio y se encargan de interactuar con fuentes de datos externas, como servicios web, bases de datos, configuraciones de usuario y archivos planos, por mencionar algunos. Su función principal es traducir la información obtenida en términos de entidades que la aplicación pueda procesar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*gvFiXU2qHLSKErlVWNrYWg.png" /></figure><p>Por ejemplo, podríamos tener una implementación de repositorio que consume un servicio web a través del protocolo HTTP y retorna las entidades correspondientes. Estas entidades podrían luego ser almacenadas en una base de datos mediante otra implementación de repositorio. La próxima vez que el caso de uso requiera la información, podría decidir obtenerla de la base de datos y servirla a su consumidor, mientras que en segundo plano se hace una operación para que el repositorio HTTP actualice base de datos con la información más reciente.</p><h3>Manejo de Dependencias</h3><p>El manejo de dependencias es un aspecto crucial en cualquier arquitectura. Aunque existen librerías de terceros para iOS que facilitan la inyección de dependencias, uno de los factores determinantes en mi arquitectura de referencia es limitar el uso de estas librerías. Por lo tanto, opté por utilizar los mecanismos proporcionados por Swift/SwiftUI.</p><h4>Primera Versión: Singleton</h4><p>La primera versión de la arquitectura utilizaba un Singleton para registrar las dependencias. Cada clase que necesitaba una dependencia accedía directamente al Singleton para obtener una referencia. Esta decisión se tomó para acelerar el desarrollo, con la intención de refactorizar en una versión futura. Aunque el patrón Singleton puede convertirse fácilmente en un anti patrón, su uso aquí estaba justificado por factores como la cantidad de desarrolladores y la necesidad de escalabilidad.</p><h4>Segunda Versión: @Environment y @EnvironmentObject</h4><p>Después de implementar algunas funcionalidades con la primera versión, la segunda versión de la arquitectura utilizaba @Environment, un mecanismo nativo de SwiftUI para acceder a información a través de las vistas. Sin embargo, @Environment solo puede usarse en el contexto de las vistas de SwiftUI y no dentro de los ViewModels. Para superar esta limitación, combiné @EnvironmentObject y ObservableObject para inyectar dependencias desde las vistas hacia los ViewModels. Esta solución, sin embargo, iba en contra de otro factor determinante: mantener la testabilidad.</p><h4>Tercera Versión: DependenciesContainer y @Injected</h4><p>En la tercera versión, decidí usar varios mecanismos en conjunto para mejorar la inyección de dependencias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*kKNa1dB-xFWXzWwcllFE0A.png" /></figure><p><strong>DependenciesContainer</strong></p><p>Se utiliza una clase para separar las dependencias por espacios de nombres (name spaces), como dependencias a nivel de ViewModels o el estado global de la aplicación:</p><pre>final class DependenciesContainer {<br>    let viewModel: ViewModelDependencies<br>    let appState: AppState<br><br>    init(viewModel: ViewModelDependencies, appState: AppState) {<br>        self.viewModel = viewModel<br>        self.appState = appState<br>    }<br>}</pre><p><strong>Property Wrapper: @Injected</strong></p><p>Implementé un property wrapper, llamado @Injected (idea tomada de <a href="https://github.com/davidgarywood/swiftui-router/blob/main/swiftui-router/Dependencies/Injected.swift">este repositorio</a>), que permite inyectar una referencia a una dependencia usando ‘KeyPath’ para apuntar al name space y la dependencia dentro de él:</p><pre>@propertyWrapper<br>struct Injected&lt;T&gt; {<br>    <br>    private let keyPath: KeyPath&lt;DependenciesContainer, T&gt;<br>    <br>    public var wrappedValue: T {<br>        DependenciesContainer.assembly[keyPath: keyPath]<br>    }<br>    <br>    init(_ keyPath: KeyPath&lt;DependenciesContainer, T&gt;) {<br>        self.keyPath = keyPath<br>    }<br>}</pre><p><strong>Función Ensambladora</strong></p><p>Una función ensambladora es llamada al inicio de la aplicación (o más específicamente en el primer uso del property wrapper) para definir las dependencias para diferentes entornos de ejecución, como previews de SwiftUI o pruebas unitarias.</p><pre>extension DependenciesContainer {<br>    static var assembly: DependenciesContainer = {<br>        /* we can use <br>        / ProcessInfo.processInfo.environment[&quot;XCODE_RUNNING_FOR_PREVIEWS&quot;] == &quot;1&quot; <br>        / to tell if we&#39;re runninf just for previews and create Mock instances<br>        */<br><br>        let urlSession = URLSession(configuration: .default)<br>        <br>        let storeInteractor = DefaultStoreInteractor(repository: HTTPStoreRepository(session: urlSession))<br>        <br>        let viewModelDependencies = ViewModelDependencies(storeInteractor: storeInteractor)<br>        return DependenciesContainer(viewModel: viewModelDependencies, appState: AppState())<br>    }()<br>}</pre><p><strong>Inyección de Dependencias</strong></p><p>Las dependencias se inyectan dentro de las clases que las requieren:</p><pre>class SearchViewModel: ObservableObject {<br>    @Injected(\.viewModel.storeInteractor) var storeInteractor<br><br>...<br>}</pre><h3>Estado actual de la arquitectura</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgTTkU_H8cVYjI5fQbFr9g.png" /></figure><p>La arquitectura de referencia sigue en construcción, pero este artículo ofrece un buen panorama de su estado actual. A medida que la aplicación de prueba crezca y enfrente nuevos desafíos, la arquitectura evolucionará y se adaptará en consecuencia.</p><h3>Conclusiones</h3><ol><li><strong>Decisiones Basadas en Factores Determinantes: </strong>Las decisiones arquitectónicas deben basarse en requisitos funcionales, no funcionales y restricciones específicas del proyecto. Cada decisión arquitectónica debe estar documentada y soportada en los posibles trade-offs o intercambios de lo que se gana contra lo que se pierde. El presente ejercicio presenta una aproximación más informal y las decisiones, consciente o inconscientemente, se sopesaron mediante <em>trade-offs</em>.</li><li><strong>Adaptabilidad y Evolución: </strong>La arquitectura de aplicaciones móviles no es estática; debe evolucionar y adaptarse a medida que la aplicación crece y enfrenta nuevos desafíos. De hecho, hay decisiones que se pueden dilatar hasta tener suficiente contexto o información para hacer el balance de los <em>trade-offs</em>. La capacidad de modificar y mejorar la arquitectura en respuesta a cambios y necesidades emergentes es crucial para el éxito a largo plazo.</li><li><strong>Importancia de la Separación de Responsabilidades:</strong> Utilizar patrones como MVVM y la inyección de dependencias ayuda a mantener una separación clara de responsabilidades. Esto no solo mejora la mantenibilidad y la claridad del código, sino que también facilita la realización de pruebas y el desarrollo colaborativo.</li><li><strong>Manejo de Dependencias:</strong> La inyección de dependencias es un componente esencial para una arquitectura flexible y robusta. Aunque existen diversas estrategias y herramientas, en este proyecto se optó por soluciones nativas de Swift/SwiftUI para mantener la simplicidad y el control.</li><li><strong>Iteración y Mejora Continua:</strong> La arquitectura presentada es solo una instantánea en el tiempo. A medida que se implementen nuevas funcionalidades y se enfrenten nuevos retos, es fundamental iterar y refinar la arquitectura. Documentar y evaluar continuamente las decisiones tomadas permitirá mejorar y adaptar la arquitectura de manera efectiva.</li><li><strong>Contexto y Escalabilidad:</strong> Las decisiones arquitectónicas deben considerar el contexto en el que se desarrollará la aplicación. Para proyectos individuales o pequeños equipos, ciertas soluciones pueden ser apropiadas, mientras que para equipos más grandes y aplicaciones más complejas, puede ser necesario adoptar enfoques más escalables y robustos.</li></ol><p>En resumen, la arquitectura de una aplicación móvil debe ser flexible, adaptativa y bien documentada para enfrentarse a los constantes cambios y retos del desarrollo de software. La elección de patrones y prácticas adecuadas, junto con una evaluación constante, son claves para construir aplicaciones robustas y sostenibles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fddfd6e85a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conteo de referencias en iOS]]></title>
            <link>https://medium.com/@jaiversin/conteo-de-referencias-en-ios-dac2d333061c?source=rss-d3b4a9b9d93------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac2d333061c</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Jhon López]]></dc:creator>
            <pubDate>Tue, 11 Dec 2018 14:54:15 GMT</pubDate>
            <atom:updated>2018-12-11T14:54:15.789Z</atom:updated>
            <content:encoded><![CDATA[<p>La primera regla del conteo de referencias es no mantener referencias (fuertes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*dqSCO7WarO_EpSvl.gif" /></figure><p>Ya sabemos que no es así de sencillo, las referencias fuertes son necesarias pero hay que tener claro cuándo hay que hacerlas débiles, es decir, identificar en dónde hay riesgo de crear un ciclo de retención de memoria. Pero primero…</p><p><strong>¿Qué es ARC?</strong></p><p><em>Automatic Reference Counting</em> o conteo de referencias automático es, a grandes rasgos, el mecanismo que usa Apple para manejar la memoria. Cada vez que se agrega una referencia fuerte a un objeto en memoria, el conteo aumenta en 1. A su vez, cuando una referencia fuerte se elimina, el conteo disminuye en 1. Cuando un objeto no tiene ninguna referencia fuerte, el espacio de memoria que utiliza, puede ser liberado o reutilizado.</p><p><strong>¿Qué es una referencia fuerte?</strong></p><p>Al declarar una variable sin utilizar ningún modificador, es decir: var objeto = AlgunaClase() estamos creando una referencia fuerte desde el contexto actual (self) hacia objeto.</p><p><strong>¿Qué es una referencia débil?</strong></p><p>Una referencia débil es la que no aumenta el conteo de referencias hacia un objeto en memoria, es decir, no evita que su espacio de memoria sea liberado. Para definirla, podemos usar dos modificadores: <strong>weak</strong> y <strong>unowned</strong>.</p><p><strong><em>weak</em></strong></p><p>Al usar el modificador weak, estamos declarando que la referencia será débil (no va a aumentar el conteo de referencias hacia objeto) por lo que en cualquier momento, durante el tiempo de ejecución, podría quedarse sin referencias fuertes desde otros objetos y se liberaría su espacio en memoria, lo que abre la posibilidad de estar haciendo referencia a nil. Gracias a Swift tenemos acceso al tipo optional (algo como una envoltura o <em>wrapper </em>que se representa con un signo de interrogación inmediatamente después del tipo, que tal vez abordaré en otro artículo) y nos permite manejar este tipo de escenarios (en realidad el compilador te obliga a que el tipo de la variable sea optional así que no es tan opcional 😜).</p><p>weak var objeto: AlgunaClase?</p><p><strong><em>unowned</em></strong></p><p>El modificador <em>unowned</em> es prácticamente igual a <em>weak</em>, pero no requiere que sea optional (tenemos que asegurarnos que la variable siempre tendrá un valor) por lo que la restricción para usar <em>unowned</em> es que tengamos completa certeza de que la instancia a la que hace referencia objeto siempre tendrá el mismo tiempo de vida que self.</p><p>unowned var objeto: AlgunaClase</p><p>Un valor agregado de <em>unowned</em> frente a <em>weak</em>, es que podemos ejecutar una función o modificar las propiedades de objeto en el proceso de liberación de memoria del objeto dueño de la referencia (self), es decir, mientras se está ejecutando la función deinit (o dealloc en Objective C) de self.</p><p><strong>¿Qué es un ciclo de retención de memoria?</strong></p><p>En pocas palabras, es cuando un objeto hace referencia fuerte a otro y este a su vez hace referencia fuerte al primero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*TYgA-73Q675zVU9_XdavZA.jpeg" /><figcaption>Ciclo de retención de memoria (Retain cycle)</figcaption></figure><p>Al tener referencias fuertes entre sí, no es posible la liberación de la memoria de ninguno de los dos objetos y lo más seguro es que se convierta en una fuga de memoria (<em>memory leak</em>). No siempre los casos en los que se presenta un ciclo de retención de memoria son tan simples o fáciles de detectar como el del gráfico, por lo que es muy importante tener esto en cuenta a la hora de hacer aplicaciones.</p><p>Un ejemplo más claro de un ciclo de retención de memoria se vería así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d60754a14f56a3f269a89cde27ab3e/href">https://medium.com/media/c8d60754a14f56a3f269a89cde27ab3e/href</a></iframe><p>Los casos más comunes de ciclos de retención de memoria se presentan con la implementación de delegados (patrón <em>delegate</em> muy comúnmente usado en el desarrollo de aplicaciones en iOS) y los <em>closure </em>o bloques de código, que Apple <a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">define</a> como:</p><blockquote><em>Closures</em> are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.</blockquote><p>Al ser bloques auto-contenidos que capturan y almacenan referencias del contexto en donde son definidos (esto lo hace Swift automáticamente), se crea el riesgo de causar una fuga de memoria.</p><p>Un posible ciclo de retención de memoria en un <em>closure </em>en el que se hace referencia<em> a </em><em>self</em> se vería así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd100be1f27244fec12f059a6ece4673/href">https://medium.com/media/bd100be1f27244fec12f059a6ece4673/href</a></iframe><p><strong>¿Cómo se evitan los ciclos de retención de memoria?</strong></p><p>En el primer ejemplo, al declarar la referencia de propietario como weak se evita la retención de memoria. Aunque aún parece haber una referencia cíclica, la referencia débil no evita la liberación de la memoria.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/807489ffb9c4746f749067f1a6f0ed65/href">https://medium.com/media/807489ffb9c4746f749067f1a6f0ed65/href</a></iframe><p>Para el caso del <em>closure</em>, la solución es definir en la lista de captura o <a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html#ID57"><em>capture list</em></a> las variables capturadas que vamos a utilizar dentro del <em>closure</em> como <em>weak.</em> Ya que sabemos que ambas instancias tienen el mismo tiempo de vida (al liberarse la memoria de la instancia de Persona, se libera la memoria de la instancia de Carro) también es posible usar <em>unowned</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f92d265b6790a275ad492aeeb85e8d7/href">https://medium.com/media/6f92d265b6790a275ad492aeeb85e8d7/href</a></iframe><p><strong>Conclusión</strong></p><p>La forma en que Apple administra la memoria deja en manos del desarrollador la gran responsabilidad de identificar cuándo usar los tipos de referencia (fuerte o débil). Las fugas de memoria no sólo generan un consumo adicional e innecesario de memoria, sino que pueden causar comportamientos erráticos e inesperados en una aplicación, por lo que siempre hay que ser cuidadoso y utilizar las herramientas que Apple proporciona para identificarlos como el Memory Graph o el Profiler (Instruments) de los cuales hablaré en siguientes artículos.</p><p>¿Quedó todo claro? ¡Si no es así, déjame un comentario y trataré de resolverlo!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac2d333061c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>