<?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[salt&amp;pepper - Medium]]></title>
        <description><![CDATA[Salt and Pepper is a full service development company partnering with startups and  large enterprises across Europe and the USA. We are skilled at helping our clients successfully define,  design and build digital products that shape the world the tomorrow. - Medium]]></description>
        <link>https://medium.com/salt-pepper?source=rss----68d628c1b9eb---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>salt&amp;amp;pepper - Medium</title>
            <link>https://medium.com/salt-pepper?source=rss----68d628c1b9eb---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:24:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/salt-pepper" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A.I Driven Software Development Workflow]]></title>
            <link>https://medium.com/salt-pepper/a-i-driven-software-development-workflow-d2ba35c106e2?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/d2ba35c106e2</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[sdlc]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 13:25:56 GMT</pubDate>
            <atom:updated>2023-04-27T13:23:31.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBS5UG91aNy_njW_8_2G6g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@skraidantisdrambliukas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gertrūda Valasevičiūtė</a> on <a href="https://unsplash.com/photos/xMObPS6V_gY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every software project has a workflow. A step of high-level steps that repeat themselves in order to create a software project.</p><p>These steps are standardized and the steps of the standard development workflow or life cycle.</p><p>The steps are:</p><ol><li><strong>Planning/ Requirement gathering</strong></li></ol><p>In the planning and the requirement gathering steps, you create the project instance on your task management system, timelines, milestones, team members, ownership, communication channels and general project setup.</p><p>Using the project management software, you assign tasks and track progress for the entire workflow.</p><p>Also, in this step, the version control system (such as GIT) and the version control strategy are set up to manage and track the source code.</p><p><strong>2. Design</strong></p><p>In the design step, you use the requirements gathered and you design the software solution. This includes UI/UX design and high-level design that outlines the architecture, components and functionality of the software.</p><p><strong>3. Implementation</strong></p><p>Once the design is complete, the development team begins writing the code for the software. This involves programming, development testing, and debugging the code to ensure that it meets the requirements and functions as intended.</p><p><strong>4. Testing/Deployment</strong></p><p>Once the code is complete, it is tested to ensure that it meets the quality standards and specifications set forth in the requirements. Testing may include unit testing, integration testing, system testing, and user acceptance testing.</p><p>After testing is complete, the software is deployed to the production environment. This involves installing the software on the production server, configuring it for the production environment, and ensuring that it is ready for use.</p><p><strong>5. Maintenance</strong></p><p>After deployment, the software is monitored and maintained to ensure that it continues to function properly. This may include bug fixes, security updates, and feature enhancements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Wm9WCSQ-8SzcRhlCz-keyA.gif" /><figcaption><a href="https://media.giphy.com/media/k74OUg6bPJKy2JmyoS/giphy.gif">https://media.giphy.com/media/k74OUg6bPJKy2JmyoS/giphy.gif</a></figcaption></figure><p>“But where does A.I. factor in? I was promised A.I. in the title of this article.”</p><p>Unfortunately, a standardized methodology for using A.I. in a software development process does not exist. Or at least, not at the time this article was written.</p><p>We are now in an experimentation phase with OpenAI’s <a href="https://chat.openai.com/">ChatGPT</a>, <a href="https://github.com/features/copilot">Github’s Copilot</a> and others. We are fumbling around, trying things, scaring ourselves needlessly with the “End is near for software engineers”, “A.I. will take our jobs” and “ChatGPT will replace programmers”. I’m kinda tired of this clickbait-ish form of content.</p><blockquote>In short: <strong>No. </strong>It will not replace programmers.</blockquote><p>Instead, <strong>if used properly</strong>, these tools will give us superpowers and our productivity will skyrocket.</p><p>A.I. has the potential to affect every step of the classic software development lifecycle or SDLC on every flavour of methodology that is based on it albeit Kanban, Waterfall, Agile or others.</p><p>Now, here is my take on how the SDLC can be improved using A.I. in the mix.</p><p>Personally, I see these A.I. tools as superpowered feedback loops for every step of the way in the workflow. Some sort of an optional sub-step in the SDLC workflow.</p><p>So, I would see it something like this:</p><ol><li><strong>Planning and requirements gathering</strong></li></ol><p>Use A.I. to generate ideas and provide feedback on the project requirements.</p><p><strong>2. Design</strong></p><p>Use A.I. to generate ideas and provide feedback on the software design.</p><p><strong>3. Implementation</strong></p><p>Use A.I. for guidance and suggestions on code snippets and for troubleshooting issues.</p><p><strong>4. Testing/ Deployment</strong></p><p>Use A.I. to create automated tests for your methods. (Ex: Unit tests generator) and to provide recommendations for deployment strategies and configurations.</p><p><strong>5. Maintenance</strong></p><p>Use A.I. to troubleshoot issues and provide guidance on bug fixes and feature enhancements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpUgWWieSeWu2k4uamMAbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Jordan</a> on <a href="https://unsplash.com/photos/wF7GqWA3Tag?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Use it like a super-enhanced rubber duck to tell it issues and then resolve those issues.</p><p>In a visual form, upgrading the standard software development lifecycle from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*uO564_ncDT71PTorgXgVbQ.png" /><figcaption>Software Development Lifecycle/Workflow</figcaption></figure><p>Will become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*QYXhHceeQdgXDPk0mOwheQ.png" /><figcaption>Using A.I. to enhance every step of the Software Development Lifecycle/Workflow</figcaption></figure><p>Again, <strong>if applied properly, </strong>this flavour of SDLC has the potential to increase the velocity of development for a team quite considerably. Or at least in theory. Experimentation in larger teams still needs to be done in order to confirm it. Personally, I’ve only tried it out on a small scale. The results are promising.</p><p>Now, let’s talk about the drawbacks.</p><p>From my point of view, the biggest risk is the <strong>certainty of knowledge</strong>. The AI models can be biased on the data that they were trained on. This can lead to errors and inaccuracies in their suggestions and recommendations. This can be quite problematic in experience design for example. They may not account for diverse user perspectives.</p><p>Another drawback is the <strong>limited capabilities</strong> and <strong>overreliance </strong>of/on A.I. Models like ChatGPT can be highly effective with simple things but they may not be able to fully understand the nuances of a specific programming language or development environment. If developers rely too heavily on AI suggestions and recommendations, they may become less proficient in certain areas of software development.</p><p>For example, if they always rely on AI to troubleshoot issues, they may not develop strong problem-solving skills themselves which in turn lowers the quality of expertise in the long run.</p><p>Some other drawbacks include but are not exclusively:</p><ul><li><strong>Security risks</strong></li></ul><p>If an AI model is used to test the security of a system, it may not identify all potential vulnerabilities and could itself become a target for attackers. This can compromise the security of the software being developed and deployed.</p><ul><li><strong>Cost</strong></li></ul><p>Developing and integrating AI into a software development workflow can be expensive and time-consuming. Not all businesses may have the necessary resources to invest in AI, which could limit their ability to compete with larger organisations that do have the resources.</p><ul><li><strong>Ethical considerations</strong></li></ul><p>As AI models become more sophisticated and are integrated into software development workflows, there are ethical considerations that need to be addressed.</p><p>For example, there may be concerns about the privacy of user data or the potential for AI to be used in ways that harm society or marginalized groups.</p><p>It’s important to note that these potential drawbacks don’t necessarily mean that integrating AI into a standard software development workflow is a bad idea. Instead, we need to be careful.</p><p>We need to plan and use these tools wisely in order to maximize their potential benefits while minimizing their potential drawbacks.</p><p>Let me know if you tried integrating some of these A.I. tools in your day-to-day work and how it went 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ba35c106e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/a-i-driven-software-development-workflow-d2ba35c106e2">A.I Driven Software Development Workflow</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game Theory]]></title>
            <link>https://medium.com/salt-pepper/game-theory-1d948a945963?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/1d948a945963</guid>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 11:47:47 GMT</pubDate>
            <atom:updated>2023-04-11T11:47:37.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVDBCSyctZZwX9zUgBDnWw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hpzworkz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hassan Pasha</a> on <a href="https://unsplash.com/photos/7SjEuEF06Zw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue — S02 #1 Decision Making</h4><p>Welcome to the second series of the Swift Problems catalogue. I really hope you liked the first series focused on common software design patterns.</p><p>This second series is focused on much broader problems, problems that spawned entire fields, especially in mathematics. We are gonna look at them through the looking glass of a software engineer and use Swift code to describe the mathematical formulas.</p><p>Of course, this article only serves as a gentle introduction to the topic at hand. The topics treated in this series are too vast to be covered in just one article. Use this paper as a starting point for exploration.</p><p>In this article, we’re gonna explore one of the most fundamental parts of being…well…being human. When faced with situations of competition and conflict, <strong>how do we make decisions?</strong></p><h3>What is Game Theory?</h3><p>Game theory studies precisely that: the science of <strong>decision-making</strong>.</p><p>This branch of mathematics aims to model the strategic interactions between different actors that have conflicting interests in order to identify the optimal decision-making strategies.</p><p>It gives you a framework for analyzing complex decision-making scenarios, predicting outcomes, and understanding how individuals or groups can improve their outcomes by cooperating or competing strategically.</p><h3>The Basics:</h3><p>Let’s start with the basics and that’s:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*yvolsTUzlD--9jZHvLqMWQ.gif" /></figure><p><strong>The Utility function</strong></p><p>Basically, it measures the wins and losses of each player at the end of a game. The main hypothesis here is to consider the concept of utility as an amount that can be measured numerically.</p><p>But how can you measure utility? It is a concept that is very subjective. One thing has more utility for a person than for another one.</p><p>Well, the objective is not to measure the absolute utility but two compare two situations in a way in which you can determine what has more utility in comparison with another. And here the concept of order relation from math comes into play.</p><p>The math expression for utility is the following.</p><pre>U(x) = f(x)</pre><p>Now, let’s switch that math expression to code:</p><pre>func calculateUtility(outcome: String) -&gt; Double {<br>    switch outcome {<br>    case &quot;Win&quot;:<br>        return 1.0<br>    case &quot;Tie&quot;:<br>        return 0.5<br>    case &quot;Loss&quot;:<br>        return 0.0<br>    default:<br>        return 0.0<br>    }<br>}</pre><p>Perfect, now it’s much clearer. Based on the string outcome the utility function returns a value.</p><p>If we want to compare utilities between them we say that:</p><pre>u &gt; v =&gt; V(u) &gt; V(v)</pre><p>In the first case before the “=&gt;” symbol we mean that <strong>u</strong> is preferred to <strong>v. </strong>It means that a player prefers the scenario with the <strong>u</strong> utility instead of the scenario with the <strong>v</strong> utility.</p><p>In the second case after the “=&gt;” symbol we mean that the value of the utility function V based on scenario <strong>u </strong>is higher than the utility function V based on scenario <strong>v</strong>.</p><p><strong>Allocation, dominance and solution</strong></p><p>Now, here are some other basic concepts that we need.</p><p>In game theory, <strong>allocation</strong> refers to the division of resources or payoffs among players in a game. This allocation can be based on multiple criteria, such as fairness, efficiency or strategic considerations. For example, in an auction game, the allocation of the item being auctioned would be the assignment of the item to the highest bidder.</p><p>We say that a win allocation with X utility &gt; a win allocation with Y utility if the utility function V(X) &gt; than the utility function V(Y).</p><p>The number of people that will see their win increase by switching from X to Y is called the effective group for X’s <strong>dominance</strong> over Y.</p><p>A strategy is said to be <strong>dominant</strong> if it is always a player’s best choice, regardless of the choices made by other players. Dominance can be either strict (i.e., the strategy is always better) or weak (i.e., the strategy is at least as good as any other). A player may have multiple dominant strategies or no dominant strategies at all.</p><p>We define a S<strong>olution</strong> as:</p><p>A group S of allocations that accomplish the following:</p><ul><li>Not a single element y from S is not dominated by another element X from S.</li><li>All allocations y that are not in S are dominated by an element X from S.</li></ul><p>This is pretty much the math definition of a solution but in other words, a solution is a concept that describes a set of outcomes that are considered desirable or optimal in some sense.</p><p><strong>The general definition</strong></p><p>Now, in game theory, a game is defined as a mathematical model that describes the interactions between multiple decision-makers (players) who have conflicting objectives.</p><p>The elements of this model (game) are the following:</p><ol><li>First and foremost, the <strong><em>players.</em></strong></li><li><strong><em>Strategies</em></strong>, which represent the total possible choices that a player has.</li><li><strong><em>Payoffs</em></strong><em> </em>are the rewards or penalties that each player receives for choosing a particular strategy.</li><li>The<strong> <em>Rules</em></strong> that govern the game, including how the payoffs are calculated and how players make their decision.</li><li><strong><em>Information</em></strong> or the amount of knowledge each player has about the game, including the strategies chosen by the other players.</li><li>Last but not least, <strong><em>Timing</em></strong><em> </em>or the sequence of events that occurs during the game, including when each player makes their decision.</li></ol><p>Let’s define a simple game where two players (Player 1 and Player 2) can choose to cooperate or defect. The payoff matrix for this game is as follows:</p><pre>        |  Cooperate  |  Defect<br>----------------------------------<br>Cooperate |  3, 3      |  0, 5<br>----------------------------------<br>Defect    |  5, 0      |  1, 1</pre><p>In this matrix, the first number in each cell represents the payoff to Player 1, while the second number represents the payoff to Player 2.</p><p>For example, if both players cooperate, they both receive a payoff of 3.</p><p>if Player 1 cooperates and Player 2 defects, Player 1 receives a payoff of 0 and Player 2 receives a payoff of 5.</p><p>Let’s put the game into code:</p><pre>// Player definition<br>enum Player: Int {<br>    case player1 = 1<br>    case player2 = 2<br>}<br><br>// Strategies<br>enum Strategy {<br>    case cooperate<br>    case defect<br>}<br><br>// Payoff matrix<br>let payoffMatrix: [[(Int, Int)]] = [<br>    [(3, 3), (0, 5)],<br>    [(5, 0), (1, 1)]<br>]<br><br>// Payoff calculation of a player based on the strategies chosen by both players<br>func calculatePayoff(player: Player, player1Strategy: Strategy, player2Strategy: Strategy) -&gt; (Int, Int) {<br>    let row = player1Strategy == .cooperate ? 0 : 1<br>    let col = player2Strategy == .cooperate ? 0 : 1<br><br>    let payoff = payoffMatrix[row][col]<br><br>    if player == .player1 {<br>        return payoff<br>    } else {<br>        return (payoff.1, payoff.0)<br>    }<br>}</pre><p>We define the <strong><em>Player</em></strong> and <strong><em>Strategy</em></strong> enums to represent the players and strategies in the game. Then, we define the <strong><em>payoffMatrix</em></strong> as a matrix of tuples, where each tuple represents the payoffs to each player for a particular combination of strategies.</p><p>Finally, we define the <strong><em>calculatePayoff()</em></strong> method that takes the strategies chosen by both players and returns the payoffs to the specified player as a tuple.</p><p>Now, this implementation demonstrates just the basic elements of a game: players, strategies and payoffs. We could extend this implementation to include the other elements of a game like information, timing and rules depending on the specifics of the game that we want to create.</p><p>Alright, alright, then the obvious question appears: how many types of games CAN we create?</p><p>The answer is…quite a few and each has its own set of characteristics and strategic considerations. Here are some of the most common types of games:</p><blockquote>Cooperative games</blockquote><blockquote>Non-cooperative games</blockquote><blockquote>Zero-sum games</blockquote><blockquote>Non-zero sum games</blockquote><blockquote>Simultaneous games</blockquote><blockquote>Sequential games</blockquote><blockquote>Perfect information games</blockquote><blockquote>Imperfect information games</blockquote><blockquote>Stochastic games</blockquote><blockquote>Symmetric games</blockquote><blockquote>Asymmetric games</blockquote><blockquote>Bayesian games</blockquote><blockquote>Evolutionary games</blockquote><blockquote>Combinatorial games</blockquote><blockquote>…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lTZPF1tx18JaZPiS2_wNbA.gif" /></figure><p>These are just a few examples of types of games that exist in game theory. There are many more variations and combinations of these types (ex: Sequential-move, zero-sum games), and each type presents its own challenges and strategic considerations for the players involved.</p><p>There are quite a lot of them and truth be told, a number of articles can be written just about one of them.</p><p>So, in this article, we will focus only on one type and that is the <strong>sum-zero</strong> type in its simplest form.</p><p><strong>Sum-zero games between two players</strong></p><p>In a sum zero game, the total payoff to the players is zero. This means that any gains made by one player come at the expense of the other player.</p><p>The classic example of a sum zero game is poker: if one player wins, the other player loses an equivalent amount. The sum of the winnings and losses is zero.</p><p>In game theory, sum zero games are studied using mathematical models that define the players’ strategies and the payoffs associated with different outcomes. These models can be used to predict how players will behave in real-world situations and to help players make optimal decisions.</p><p>Another important concept in sum zero games is “dominant strategies”. A dominant strategy is a strategy that is the best option for a player, regardless of the other player’s actions. For example, in a game of rock-paper-scissors, there is a dominant strategy for each player: always choose rock, paper, or scissors, respectively. This ensures that the game is fair and neither player has an advantage.</p><p>In order to model a sum zero game, we need to define the following:</p><ul><li>Players: in this case, we have two players, player1 and player2</li><li>Strategies: in this game, each player can choose one of three possible strategies: rock, paper, or scissors.</li><li>Payoff: the payoff is the gain or loss of a player based on the outcome of the game. If a player wins the other one loses.</li></ul><p>Let’s put the game into code:</p><pre>// Strategy Definition<br>enum Strategy {<br>    case rock<br>    case paper<br>    case scissors<br>}<br><br>// Player Definition<br>enum Player: Int {<br>    case player1 = 1<br>    case player2 = 2<br>}<br><br>// Define the payoff matrix<br>let payoffMatrix: [[Int]] = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]<br>// In this matrix, the row player is player 1 and the column player is player 2<br>// The first index of the matrix corresponds to the strategy of player 1, and the second index corresponds to the strategy of player 2<br><br>// Payoff value of a player based on the strategies chosen by both players<br>func calculatePayoff(player: Player, player1Strategy: Strategy, player2Strategy: Strategy) -&gt; Int {<br>    let row = player1Strategy.hashValue<br>    let col = player2Strategy.hashValue<br>    let payoff = payoffMatrix[row][col]<br>    if player == .player1 {<br>        return payoff<br>    } else {<br>        return -payoff<br>    }<br>}<br><br>// Example usage<br>let player1Strategy = Strategy.rock<br>let player2Strategy = Strategy.paper<br>let player1Payoff = calculatePayoff(player: .player1, player1Strategy: player1Strategy, player2Strategy: player2Strategy) // returns -1<br>let player2Payoff = calculatePayoff(player: .player2, player1Strategy: player1Strategy, player2Strategy: player2Strategy) // returns 1</pre><p>In this implementation, we define the strategies, players, and payoff matrix as enums. We then define a function to calculate the payoff of a player based on the strategies chosen by both players. Finally, we put them all together and we calculate the payoffs of <strong><em>player1</em></strong> and <strong><em>player2</em></strong> given their strategies.</p><p>Alright, but what do we do if we want to improve our odds? Well, we can try to change our strategy. But till what end?</p><p>One key concept in sum zero games is the “Nash equilibrium”. This is a situation in which neither player can improve their outcome by changing their strategy, given the other player’s strategy. In other words, both players are playing optimally, given the other player’s actions.</p><p><strong>Nash’s equilibrium</strong></p><p>The Nash equilibrium is a solution concept for non-cooperative games, where players are assumed to be rational and strategic. In such games, each player’s payoff depends not only on their own actions but also on the actions of their opponents. The Nash equilibrium is a set of strategies, one for each player, such that no player can improve their payoff by unilaterally changing their strategy, given the other players’ strategies.</p><p>In other words, it is a situation where both players are making the best decision given the decision of the other player.</p><p>To find the Nash equilibrium of the above rock-paper-scissors game, we need to identify the strategies that each player will choose given the strategies of the other player. In a sum zero game, the Nash equilibrium occurs when both players choose their strategies randomly with equal probabilities, since this ensures that the expected payoff for each player is zero, and neither player can unilaterally improve their payoff.</p><p>Let’s update our code from above:</p><pre>// Strategy definition<br>enum Strategy {<br>    case rock<br>    case paper<br>    case scissors<br>    <br>    static func random() -&gt; Strategy {<br>        let allValues = [rock, paper, scissors]<br>        let randomIndex = Int.random(in: 0..&lt;allValues.count)<br>        return allValues[randomIndex]<br>    }<br>}<br><br>// Player definition<br>enum Player: Int {<br>    case player1 = 1<br>    case player2 = 2<br>}<br><br>// Payoff matrix definition<br>let payoffMatrix: [[Int]] = [[0, -1, 1], [1, 0, -1], [-1, 1, 0]]<br><br>// Provides Payoff value of a player based on the strategies chosen by both players<br>func calculatePayoff(player: Player, player1Strategy: Strategy, player2Strategy: Strategy) -&gt; Int {<br>    let row = player1Strategy.hashValue<br>    let col = player2Strategy.hashValue<br>    let payoff = payoffMatrix[row][col]<br>    if player == .player1 {<br>        return payoff<br>    } else {<br>        return -payoff<br>    }<br>}<br><br>// Find the Nash equilibrium<br>let strategy1 = Strategy.random()<br>let strategy2 = Strategy.random()<br>let player1Payoff = calculatePayoff(player: .player1, player1Strategy: strategy1, player2Strategy: strategy2)<br>let player2Payoff = calculatePayoff(player: .player2, player1Strategy: strategy1, player2Strategy: strategy2)<br>if player1Payoff == 0 &amp;&amp; player2Payoff == 0 {<br>    print(&quot;Nash equilibrium: player 1 chooses \(strategy1), player 2 chooses \(strategy2)&quot;)<br>} else {<br>    print(&quot;No Nash equilibrium found&quot;)<br>}</pre><p>In this implementation, we define a <strong><em>random()</em></strong> function for the <strong><em>Strategy</em></strong> enum that chooses a random strategy with equal probabilities. We then use this function to find the Nash equilibrium of the game by choosing a random strategy for each player and checking if the resulting payoffs are both zero.</p><p>If they are, we print out the strategies as the Nash equilibrium; otherwise, we print out that no Nash equilibrium was found. Note that since the game of Rock-Paper-Scissors is also a <a href="https://en.wikipedia.org/wiki/Symmetric_game#:~:text=In%20game%20theory%2C%20a%20symmetric,then%20a%20game%20is%20symmetric.">symmetric game</a>, there are multiple Nash equilibria where both players choose their strategies randomly with equal probabilities.</p><p>The Nash equilibrium is a powerful tool for predicting behaviour in many different types of games, including auctions, bargaining, and voting. It has also been used to study social phenomena such as cooperation, trust, and the evolution of social norms.</p><p>However, the Nash equilibrium has some limitations.</p><blockquote>First, it assumes that players are rational and have complete information about the game. In reality, players may have limited information, may not be perfectly rational, or may be motivated by factors that go beyond simple self-interest.</blockquote><blockquote>Second, the Nash equilibrium may not always exist or may be multiple, which can make it difficult to apply in practice.</blockquote><p>Despite these limitations, the Nash equilibrium remains an important concept in game theory and social science. Its insights have been used to develop better strategies for negotiation, conflict resolution, and economic policy, and its influence can be seen in many areas of modern life.</p><p><strong>Nash’s disequilibrium</strong></p><p>While the Nash equilibrium represents a stable solution where no player has the incentive to change their strategy, the Nash disequilibrium represents a situation where players have the incentive to deviate from their current strategies.</p><p>In a Nash disequilibrium, one or more players have an incentive to change their strategies, which creates a situation of instability and uncertainty. This can lead to a range of outcomes, including a new equilibrium, a cycle of oscillation between strategies, or even a complete breakdown of the game.</p><p>In our case, if one player always plays <strong>Rock</strong>, the other player can exploit this by always playing <strong>Paper</strong>, resulting in a higher payoff for the second player. This leads to a state of disequilibrium, where one or both players may be motivated to change their strategy in order to achieve a higher payoff.</p><p>The Nash disequilibrium can arise in many different types of games, including those involving strategic alliances, asymmetric information, and incomplete contracts. It is an important concept because it highlights the limits of the Nash equilibrium as a predictive tool for real-world situations.</p><p>While the Nash equilibrium remains a useful and influential concept in game theory and social science, the Nash disequilibrium reminds us that not all situations can be easily modeled using a simple equilibrium framework.</p><p>In some cases, the best strategy may be to intentionally create disequilibrium, for example by using strategic shocks or other tactics to disrupt the stability of the game. Understanding both equilibrium and disequilibrium is essential for making optimal decisions in complex strategic situations.</p><h3>Real-World Usage:</h3><p>Ok, ok…so, this intro into game theory looks nice…but what can I do with it you may ask. Well…you can enhance your knowledge of this mathematical framework and take game theory into game practice.</p><p>There are a plethora of fields in which you can apply this mathematical framework. To name a few, fields like:</p><ul><li><strong>Economics</strong> where you can model and analyze markets, auctions and the dynamics of price competition.</li><li><strong>Law </strong>where you can<strong> </strong>model and analyze legal disputes and decision-making. See the behaviour of litigants in legal disputes, the effects of legal rules and regulations on social behaviour and the dynamics of legal negotiations.</li><li><strong>Biology</strong> where you can study the evolutionary dynamics and the behaviour of animals and plants in different ecological contexts. You can study the evolution of cooperation, how predators and prey behave and the dynamics of social interactions within groups.</li><li><strong>Political science</strong> where you can model and analyze political decision-making, voting behaviour, international relations and the behaviour of political parties.</li><li><strong>Computer science</strong> where you can model and analyze algorithms, network usage, the behaviour of users in online social media, and the performance of distributed computing systems.</li></ul><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this article is only a gentle introduction to Game Theory. If you want to go further and in more detail, I recommend starting with the book that started it all. You can find it <a href="https://www.amazon.com/Theory-Games-Economic-Behavior-Commemorative/dp/0691130612">here</a>.</p><blockquote><em>This is the first article in the second series of the Swift Problems Catalogue. In this series I’ll tackle different problems and provide an overview on them with a software development looking glass. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d948a945963" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/game-theory-1d948a945963">Game Theory</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run a Vapor Application on a Raspberry PI with Ubuntu 20.4]]></title>
            <link>https://medium.com/salt-pepper/how-to-run-a-vapor-application-on-a-raspberry-pi-with-ubuntu-20-4-4ca39a8d5d7e?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/4ca39a8d5d7e</guid>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 09:24:00 GMT</pubDate>
            <atom:updated>2023-03-07T09:02:41.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUEjbbE0Cl91mdEnOeh63Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zugr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Zugr</a> on <a href="https://unsplash.com/s/photos/vapor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently I have been doing some research into Distributed Querying in IoT networks.</p><p>Long story short, in the P.O.C that I’ve built for my research I’ve needed to deploy a server on a Raspberry PI. I went with Vapor just for the convenience of writing everything in Swift (both client and server-side apps) but things were a little bit trickier than I have originally expected.</p><blockquote>Vapor is a popular web framework written in Swift that can be used to create server-side applications.</blockquote><p>In this article, I’ll guide you through the process of deploying a Vapor web server on a Raspberry Pi running Ubuntu 20.04.</p><p>There are some prerequisites though…before we begin, you’ll need to make sure that you have the following:</p><ul><li>1 x Raspberry Pi</li><li>basic understanding of the command line interface</li><li>sudo privileges</li></ul><p><strong>Step 1: Install Ubuntu 20.4</strong></p><p>You can do this by using the Raspberry PI <a href="https://www.raspberrypi.com/software/">imager</a>. You need to plug an SD card into your computer and use this software to do the rest. In the choose OS — select Ubuntu 20.4 and choose storage-select the SD card.</p><p><strong>Step 2: Install Swift</strong></p><p>Vapor is built using the Swift programming language, so the first step is to install Swift on your Raspberry Pi. You can do this by following these steps:</p><ol><li>Open a terminal window on your Raspberry Pi or SSH into it 😉</li><li>Run the following command to download the Swift package:</li></ol><pre>curl -s https://packagecloud.io/install/repositories/swift-arm/release/script.deb.sh | sudo bash</pre><p>3. Run the following command to install the swift language package:</p><pre>sudo apt install swiftlang</pre><p>4. Update the swift packages:</p><pre>sudo swift package update</pre><p>You can verify that Swift is installed and working by running the following command:</p><pre>swift --version</pre><p>You will know that everything is alright when the output will show the Swift version number.</p><p>Till here, you have everything in order to run a Vapor project. You can just git clone your project, cd into its directory and run the following commands:</p><pre>sudo swift build</pre><p>and then just:</p><pre>sudo swift run</pre><p>You know you’ve made it when:</p><pre>[ NOTICE ] Server starting on http://127.0.0.1:8080</pre><p>OR if you want to create a Vapor project from scratch:</p><p><strong>Step 3: Install Vapor</strong></p><p>Now that you have Swift installed, you can install Vapor by following these steps:</p><ol><li>Run the following command to install Vapor</li></ol><pre>sudo apt install vapor</pre><p>2. Verify that Vapor is installed by running the following command:</p><pre>vapor --version</pre><p>You will know that everything is alright when the output will show the Vapor version number.</p><p><strong>Step 4: Create a new Vapor Project</strong></p><p>Now that you have Vapor installed, you can create a new Vapor project by following these steps:</p><ol><li>Run the following command to create a new Vapor project:</li></ol><pre>vapor new myproject</pre><p>This creates a new Vapor project named “myproject” in the current directory.</p><p>3. Navigate into the new project directory by running the following command:</p><pre>cd myproject</pre><p>You can now build and run your Vapor project by following these steps:</p><p>4. Run the following command to build your project:</p><pre>vapor build --arch arm64</pre><p>5. Run the following command to run your project:</p><pre>vapor run serve --hostname 0.0.0.0 --port 8080</pre><p>This command runs your project and binds it to the IP address 0.0.0.0 and port 8080.</p><p>6. Open a web browser and navigate to http://&lt;your_raspberry_pi_ip_address&gt;:8080. You should see the Vapor “Hello, world!” message displayed in your browser.</p><p>And that’s it ✨… but there are a couple of things that we can do that more or less go hand in hand with deploying a server.</p><p>The following steps are marked as optional. You don’t necessarily need to add them if you don’t require them.</p><p><strong>[Optional] Step 5: Install PostgreSQL</strong></p><p>Usually, when using a webserver, we also need a database server. You can use the following command to install a PostgreSQL server.</p><pre>sudo apt-get install openssl libssl-dev zlib1g-dev libsqlite3-dev</pre><p><strong>[Optional] Step 6: Deploy Vapor Project as a Systemd Service</strong></p><p>Now that your Vapor project is up and running, you may want to set it up as a systemd service so that it starts automatically at boot. Here are the steps to do that:</p><ol><li>Create a new file in the /etc/systemd/system/ directory named myproject.service:</li></ol><pre>sudo nano /etc/systemd/system/myproject.service</pre><p>2. Paste the following contents into the file:</p><pre>[Unit]<br>Description=MyProject Vapor Web Server<br><br>[Service]<br>User=&lt;your_username&gt;<br>WorkingDirectory=/path/to/myproject<br>ExecStart=/usr/bin/vapor run serve --hostname 0.0.0.0 --port 8080<br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Be sure to replace &lt;your_username&gt; with your actual username and /path/to/myproject with the path to your Vapor project directory.</p><p>3. Save and close the file.</p><p>4. Run the following command to reload the systemd configuration:</p><pre>sudo systemctl daemon-reloadsudo apt update</pre><p>5. Run the following command to start the myproject service:</p><pre>sudo systemctl start myproject</pre><p>6. Run the following command to enable the myproject service to start automatically at boot:</p><pre>sudo systemctl enable myproject</pre><p>You can now reboot your Raspberry Pi, and your Vapor project will start automatically as a systemd service.</p><p>From this point on, the sky is the limit 🚀</p><p>Let me know what you think and don’t be shy to share your story if you ever needed to deploy Vapor on a Raspberry PI 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ca39a8d5d7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/how-to-run-a-vapor-application-on-a-raspberry-pi-with-ubuntu-20-4-4ca39a8d5d7e">How to run a Vapor Application on a Raspberry PI with Ubuntu 20.4</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Separate algorithms from the objects on which they operate]]></title>
            <link>https://medium.com/salt-pepper/separate-algorithms-from-the-objects-on-which-they-operate-60feb52e9f68?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/60feb52e9f68</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 09:05:44 GMT</pubDate>
            <atom:updated>2023-02-28T09:02:43.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_blpUfNvY4rXdHsRqiKN-w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@namroud?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Namroud Gorguis</a> on <a href="https://unsplash.com/images/things/music?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #22</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement an application that allows users to organize and play their music tracks.</p><p>Considering that could be multiple tracks and categories, and different operations on the tracks, we need a way to separate the management of tracks from the operations that can be performed on them in order to support an easy way to add new operations or make changes on them.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Visitor </strong>it’s a behavioral design pattern that separates an algorithm from an object structure on which it operates. The pattern defines a new type of object, called a visitor, that has methods for visiting each type of element in the object structure. The elements accept the visitor and use it to perform the operation.</blockquote><p>It allows you to add new operations to the elements of an object structure without changing the classes of the elements. The elements have a common protocol and specific classes of Visitors. When a Visitor is passed to an element, it calls the corresponding visit method on the visitor who performs the operation.</p><h3>Real-World Usage:</h3><p>First, we need to define aMusicTrack protocol that has a single method, accept(visitor:), which will be used to accept a visitor.</p><p>Afterwards, we need to define the Song and Podcast classes which are concrete implementations of the MusicTrack protocol. They represent different types of tracks that can be visited. The artist and title properties in the Song class, and the title and episode properties in the Podcast class, are used to store information about the track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*OvQCQM53MTE1M1m0CT2nyA.png" /><figcaption>1. Music Track</figcaption></figure><p>Next, we need to define the MusicTrackVisitor protocol that has two methods, visit(track: Song) and visit(track: Podcast), which are used to perform operations on tracks of the corresponding type.</p><p>Afterwards, we need to define a MusicLibraryVisitor class which is a concrete implementation of the MusicTrackVisitor protocol, it defines an operation that can be performed on tracks. It has two properties songs and podcasts which will be used to store the visited tracks, it adds the visited tracks to corresponding arrays.</p><p>The key idea of this pattern is that elements have a common protocol and specific classes of Visitors. When a Visitor is passed to an element, it calls the corresponding visit method on the visitor which performs the operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNP3mjauU9CnprLXYnhhzg.png" /><figcaption>2. Visitor</figcaption></figure><p>Finally, let’s bring everything together by creating some songs, some podcasts and a visitor object.</p><p>When a song or a podcast is passed to the accept(visitor:) method, it calls the visit(track: Song) or visit(track: Podcast) method on the visitor, which in turn will add the track to the corresponding array.</p><p>This way each track will call the corresponding visit method on the visitor, adding the track to the corresponding array, and then we print the songs and podcasts array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_5BfbHlbyo2_EudlZ8iAA.png" /><figcaption>3. Bringing everything together</figcaption></figure><p>The Visitor pattern allows you to add new operations to the elements of an object structure without changing the classes of the elements. The pattern defines a new type of object, the visitor, that has methods for visiting each type of element in the object structure. The elements accept the visitor and use it to perform the operation.</p><p>Without using the Visitor pattern, the operations would need to be included in the Song and Podcast classes, which would make it difficult to add new operations or make changes to existing ones without affecting the classes themselves.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60feb52e9f68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/separate-algorithms-from-the-objects-on-which-they-operate-60feb52e9f68">Separate algorithms from the objects on which they operate</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make objects interchangeable in a family of business logic]]></title>
            <link>https://medium.com/salt-pepper/make-objects-interchangeable-in-a-family-of-business-logic-23e787c023fd?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/23e787c023fd</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 10:49:31 GMT</pubDate>
            <atom:updated>2023-02-21T09:02:18.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgKNp5oBNBlAm4ow4SsQYQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/de/@derstudi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Timon Studler</a> on <a href="https://unsplash.com/photos/BIk2ANMmNz4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #21</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement a game where you have different characters that can jump with different styles.</p><p>The game allows players to change the jumping styles of their character dynamically, depending on the current situation. We need a way to define different kinds of algorithms (one for every jump style) and interchange them at will.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Strategy </strong>it’s a behavioral design pattern that defines a family of algorithms, encapsulates each one of them and make them interchangeable. The pattern lets the algorithm vary independently from the clients that use it.</blockquote><p>In essence, it defines a common interface for algorithms, so that the client code can work with any concrete strategy without knowing its class. The client code holds a reference to a strategy and uses it to execute the algorithm. The client can change the strategy dynamically at runtime, depending on the situation.</p><h3>Real-World Usage:</h3><p>First, we need to define aJumpStrategy protocol that has a single method, jump(), which is used to perform a specific jumping style.</p><p>The ShortJump and LongJump classes are concrete implementations of the JumpStrategy protocol, they define different jumping styles that can be performed. Each class has a single method jump() that will be called when the character wants to perform a jump and a message is printed to indicate the type of jump.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*IOcz1QmbNx8wdy4keWKLiw.png" /><figcaption>1. Jump Strategy</figcaption></figure><p>Next, we define a Character class that holds a reference to a jump strategy object, it is initialized with one of the jump strategy implementations and it has a method jump() which triggers the execution of the jump strategy.</p><p>In this way, the character can change the jump style dynamically, depending on the current situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*R5q5XXNO0PQJGareky1OlQ.png" /><figcaption>2. Character</figcaption></figure><p>Finally, let’s bring everything together by creating a character with a short jump style and then calling the jump() method on the character, which causes the character to perform a short jump and the message &quot;Short Jump&quot; is printed.</p><p>Then we change the character&#39;s jump strategy to long jump, and again call the jump() method on the character, which causes the character to perform a long jump and the message &quot;Long Jump&quot; is printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*OT_4GdUvg92PlhNcEE3vOw.png" /><figcaption>3. Bringing everything together</figcaption></figure><p>The strategy pattern allows you to define a family of jumping styles, encapsulate each one of them and make them interchangeable. The character that uses the jump strategy doesn’t need to know the details of the jump, it only needs to know that it exists and what it does. This way the character can change the jump dynamically, depending on the current situation.</p><p>This pattern is useful when you have multiple jumping styles that need to be used in different situations and you want to avoid using if-else or switch-case statements to choose the right jumping style and also make it easy to add new jumping styles or change existing ones without affecting the character code.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e787c023fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/make-objects-interchangeable-in-a-family-of-business-logic-23e787c023fd">Make objects interchangeable in a family of business logic</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Save and restore the previous state of an object]]></title>
            <link>https://medium.com/salt-pepper/save-and-restore-the-previous-state-of-an-object-a83c87bcf79f?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/a83c87bcf79f</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 11:50:33 GMT</pubDate>
            <atom:updated>2023-02-07T09:02:42.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6XlDgrNl1MiM5fvVdZIFTw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@onurbuz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Onur Buz</a> on <a href="https://unsplash.com/photos/zwKoA_0CWgg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #19</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement a video game 👾Players will take on the role of a hero, building up their strength and abilities as they progress through the game.</p><p>One of the key features of our game is the ability to save and load progress. We need a way for players to save their game at any point and then come back to it later to continue their adventure.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Memento </strong>it’s a behavioral design pattern that allows an object to save and restore its internal state without violating encapsulation.</blockquote><h3>Real-World Usage:</h3><p>First, we need to define aGameSave protocol that has two properties, player and enemies .This protocol defines the state of the player and enemies respectively.</p><p>The ConcreteGameSave class is a concrete implementation of the GameSave protocol, it has two private variables player and enemies which are set at initialization, this class holds the state of the game at a particular moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*sd4-ddog8mYBW7X59zZv9A.png" /><figcaption>1. Game Save Definition</figcaption></figure><p>Next, we need a Player class that represents the player of the game and has properties like name, level, health, experience, inventory. It has two methods:</p><ul><li>createGameSave() method creates a new game save with the player&#39;s current state and enemies. This method is used to save the current state of the game.</li><li>setGameSave(_:) method sets the player&#39;s state and enemies to the state stored in the save passed as an argument. This method is used to restore the game to a previous state.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5GNAgiMLd79zTmJ2N2_ow.png" /><figcaption>2. Player</figcaption></figure><p>Afterwards, we need anEnemy class that represents the enemies of the game and has properties like name, level, health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*-vc4T2UR9E9GhcXWM-3_ug.png" /><figcaption>3. Enemy</figcaption></figure><p>Then, we define aGame class as a singleton that holds the enemies and the player. It has two methods save() and load(_:) that allows the player to save and load their progress respectively.</p><p>save() method calls the createGameSave() method on the player object to create a new save with the player&#39;s current state and enemies.</p><p>load(_:) method takes a game save as an argument and calls the setGameSave(_:) method on the player object to restore the player and enemies to the state stored in the save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAxjy-AJgPPbBAx7kiTMdg.png" /><figcaption>4. Game</figcaption></figure><p>So, in practice, when the player wants to save their progress, the save() method is called, this creates a new save with the current state of the player and enemies, and the game save is saved to be used later. When the player wants to load their progress, the load(_:) method is called, it takes a game save as an argument and sets the player and enemies to the state stored in the save, restoring the game to the previous state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FH1D6MVRza96pOFDRhzv1w.png" /><figcaption>5. Bringing everything together</figcaption></figure><p>This way the player can save their progress and restore it later without violating encapsulation. The player’s state is saved separately from the player object, so the player object can be restored to a previous state without having to know the details of how it was saved.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a83c87bcf79f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/save-and-restore-the-previous-state-of-an-object-a83c87bcf79f">Save and restore the previous state of an object</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce chaotic dependencies between objects]]></title>
            <link>https://medium.com/salt-pepper/reduce-chaotic-dependencies-between-objects-9fba72919839?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/9fba72919839</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 09:19:32 GMT</pubDate>
            <atom:updated>2023-01-31T09:02:33.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5vXsXEs5DtBQ0jVxvRZoQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@zhpix?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pascal Meier</a> on <a href="https://unsplash.com/photos/UYiesSO4FiM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #18</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement an air traffic control simulation app where users can control different aircraft and communicate with other aircraft.</p><p>The app would have a main interface where users can select an aircraft and send messages to other aircraft, such as requesting permission to take off or land. Due to the fact that there is a lot of aircraft that need to talk with one another, we can quickly slip into references hell and resulting in a highly tightly coupled system.</p><p>We need a way to allow loose coupling between all aircraft in order to make it easy to extend or modify.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Mediator </strong>it’s a design pattern that is used to manage communication between objects and promote loose coupling between them.</blockquote><h3>Real-World Usage:</h3><p>First, we need to define aMediator protocol with two methods:registerAircraft(aircraft: Aircraft) and send(message: String, aircraft: Aircraft) that will be implemented by concrete mediator classes.</p><p>Next, we need to define anAircraft protocol that has two methods: send(message: String) and receive(message: String) that will be implemented by concrete aircraft classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*3jJ-Lt7F69XdjBejmdvDOg.png" /><figcaption>1. Protocols Definition</figcaption></figure><p>Now, we need to implement theAirTrafficControlMediator class, which is the concrete implementation of the Mediator protocol and holds references to Aircraft objects and it forwards messages between them.</p><p>When an aircraft wants to send a message, it calls the send(message: String) method on itself, which in turn calls the send(message: String, aircraft: Aircraft) method on the AirTrafficControlMediator object. The AirTrafficControlMediator then forwards the message to all other aircraft, except the one that sent the message.</p><p>The AirTrafficControlMediator also keeps track of all the aircraft that have been registered with it, so it knows where to forward the messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*IZxPwcGwpw9KCOqdkAmNBg.png" /><figcaption>2. Air Traffic Control Mediator</figcaption></figure><p>The Boeing747 and AirbusA320 classes implement the Aircraft protocol and they hold a reference to an AirTrafficControlMediator object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*uB_QCsCPkY8AyeC0JasREQ.png" /><figcaption>3. Aircraft Definition</figcaption></figure><p>Finally, let’s bring everything together, let’s create an instance of the AirTrafficControlMediator() and pass it to the instances of the Boeing747 &amp; AirbusA320 .</p><p>When theboeing.send(message: &quot;Requesting permission to land.&quot;) method is called, which in turn calls the send(message: String) method on the boeing object. The boeing object then forwards the message to the AirTrafficControlMediator object by calling the send(message: String, aircraft: Aircraft) method. The AirTrafficControlMediator forwards the message to all other aircrafts by calling the receive(message: String) method on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrpRgJMei7oSd-79PeGEuQ.png" /><figcaption>4. Bringing everything together</figcaption></figure><p>By using a mediator, the aircraft objects (ex: boeing, airbus etc) don’t need to know about each other in order to communicate and they don’t have direct reference to one another, all communication goes through the mediator.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the seventh article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fba72919839" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/reduce-chaotic-dependencies-between-objects-9fba72919839">Reduce chaotic dependencies between objects</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn a request into an object]]></title>
            <link>https://medium.com/salt-pepper/turn-a-request-into-an-object-8eccf53ca83?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/8eccf53ca83</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 10:02:09 GMT</pubDate>
            <atom:updated>2023-01-24T09:02:37.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6d3AxsfHH0pTAIGgQeF2Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mostafarzq?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">mostafa rzq</a> on <a href="https://unsplash.com/photos/OWRNdpsT29Q?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #17</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement an app that allows users to control the lights in their home remotely. The user can turn lights on and off, dim them, and set schedules for when the lights should turn on and off.</p><p>The app will be developed and released in several phases. We need a way to separate the user interface elements that initiate actions from the classes that know how to perform them in order to make it easy to add new functionality, such as new types of lights or new features, without having to change the existing code.</p><h3>Problem Solution:</h3><blockquote><strong>Solution — Command pattern </strong>is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undo/redo.</blockquote><h3>Real-World Usage:</h3><p>First, we define a protocol Command that has a single method execute().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*CITTtoXtYxpWF9202KRzxA.png" /><figcaption>1. Command Protocol</figcaption></figure><p>Second, we define a Light class that has two methods: turnOn() and turnOff() that are used by the concrete commands that we will define next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*5vp3ArBB2nceNfEVRTeGBA.png" /><figcaption>2. Light Class</figcaption></figure><p>The Command protocol is implemented by two classes LightOnCommand and LightOffCommand. These two classes are concrete commands that know how to perform the request. They hold a reference to the Light object and call the corresponding method on it when the execute() method is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*XU5l0pM_eY7WudGg-EF3Tw.png" /><figcaption>3. Commands</figcaption></figure><p>Next, we define a Switch class that holds references to Command objects for turning on and off the light and it has methods flipUp() and flipDown() which execute the commands. The Switch class holds a reference to both onCommand and offCommand and it executes it when the corresponding flipUp() or flipDown() method is called.</p><p>When the flipUp() method is called, in turn calls the execute() method on the onCommand object. The onCommand object then calls the turnOn() method on the light object, which causes the string &quot;The Light is on.&quot; to be printed to the console.</p><p>Similarly, when the flipDown() method is called, it calls the execute() method on the offCommand object, which in turn calls the turnOff() method on the light object, which causes the string &quot;The Light is off.&quot; to be printed to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*kx7JNZQswBUI9A87gG6btA.png" /><figcaption>4. Switch class</figcaption></figure><p>Finally, we bring everything together. We create an instance of the Light() class and instances of the concrete commands and we pass the light instance to the instantiated commands.</p><p>We then create a Switch instance and we pass the commands. By executing the flipUp() and flipDown() methods, in turn we execute the commands which in turn execute the turnOn() and turnOff() methods defined in the Light class thus having an encapsulated request into an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLxhb4PVUTd_Zp1bVFP-pA.png" /><figcaption>5. Bringing everything together</figcaption></figure><p>The advantage of using the Command pattern is that it decouples the object that invokes the operation from the one that knows how to perform it. It allows you to pass method calls as method arguments, delay or queue a request’s execution, and support undo/redo.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eccf53ca83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/turn-a-request-into-an-object-8eccf53ca83">Turn a request into an object</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterate through the elements of a collection]]></title>
            <link>https://medium.com/salt-pepper/iterate-through-the-elements-of-a-collection-539e9f084228?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/539e9f084228</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 08:13:27 GMT</pubDate>
            <atom:updated>2023-01-17T09:01:48.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytSMqPf5CKDDBM2AjyFnKQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@foovisuals?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Foo Visuals</a> on <a href="https://unsplash.com/photos/5AMSZcgN_cM?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #16</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement an app for a restaurant that allows users to browse the menu and place orders. The app would need to go through a collection of menu items, displaying information and images for each one as the user scrolls through the menu.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Iterator Pattern </strong>it’s a design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It allows the traversal of a collection of items in a uniform way, regardless of the implementation of the collection.</blockquote><h3>Real-World Usage:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Eu5sw4RUrxXfDqNm7KN18A.png" /><figcaption>1. Menu Iterator &amp; Menu Protocols</figcaption></figure><p>First thing first, let’s start with the good ole’ protocol definitions.</p><p>The ‘MenuIterator’ protocol defines two methods that all iterator objects must implement:</p><p>‘hasNext() -&gt; Bool’: This method returns ‘true’ if there are more items to iterate over, and ‘false’ otherwise.</p><p>‘next()-&gt; MenuItem?’: This method returns the next menu item if there is one or ‘nil’ if there are no more items to iterate over.</p><p>The ‘Menu’ protocol defines one method that all objects that represent a menu must implement:</p><p>‘createIterator()-&gt;MenuIterator’: This method returns an object that implements the ‘MenuIterator’ protocol and can be used to iterate over the menu’s items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*ny5DsaZObRWRJpIz0EwtEw.png" /><figcaption>2. MenuItem Struct</figcaption></figure><p>Second, let’s define the ‘MenuItem’ struct. This represents the menu items with various properties like name, description, isVegetarian, and price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpSl7Isyo40uM5AILH5a5g.png" /><figcaption>3. DinerMenuIterator &amp; DinerMenu</figcaption></figure><p>Third, we need to create a ‘DinerMenuIterator’, which conforms to the ‘MenuIterator’ protocol that keeps track of the current position in an array of ‘MenuItem’ objects.</p><p>‘DinerMenu’ is an implementation of the ‘Menu’ protocol that holds an array of ‘MenuItem’ objects and can create an iterator for that array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68IQcP88GxPGMZJnWJtkSQ.png" /><figcaption>4. Bringing everything together</figcaption></figure><p>Last but not least, we create a DinerMenu instance and add some menu items to it using the ‘addItem’ method. Then, we use the ‘createIterator()’ method to create an iterator for the menu and assign it to a variable called ‘iterator’.</p><p>We use a ‘while’ loop to iterate over the menu items using the ‘hasNext()’ and ‘next()’ methods of the iterator. At each iteration of the loop, the ‘next()’ method returns the next menu item, and we print out the name, description and price. If there are no more items to iterate over, the ‘hasNext()’ method will return ‘false’ and the loop will exit.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539e9f084228" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/iterate-through-the-elements-of-a-collection-539e9f084228">Iterate through the elements of a collection</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pass a request along a chain of handlers]]></title>
            <link>https://medium.com/salt-pepper/pass-a-request-along-a-chain-of-handlers-244dcf79e406?source=rss----68d628c1b9eb---4</link>
            <guid isPermaLink="false">https://medium.com/p/244dcf79e406</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Alex Ilovan]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 06:23:16 GMT</pubDate>
            <atom:updated>2022-11-22T06:23:02.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUvJxxSbmceoCZ1W6mg9WQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kar111?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Karine Avetisyan</a> on <a href="https://unsplash.com/s/photos/chain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Swift — Problems Catalogue #15</h4><h3>Problem Definition:</h3><p>Consider the following scenario. You have to implement a Witch App (taking into account that Halloween was not so long ago). It has a full set of social community features for witches with all the bells and whistles including a summoning portal, a rent a broom and sharing their latest potions.</p><p>For this article, we are going to focus only on creating the potion recipes (*only the gist of how to create ingredients that depend on each other for the potion). We need a way to create a request and pass it along to different handlers.</p><p>If the handler is compatible with the request then it performs some logic, if not, it passes the request to the next handler.</p><p>In our case, it’s a possible solution to create potion recipes that have multiple dependent ingredients on each other. The cool thing about it is that multiple objects can handle the request without coupling to the concrete class of the receivers.</p><h3>Problem Solution:</h3><blockquote><strong>Solution —Chain of Responsibility — </strong>it’s a behavioral design pattern that allows you to pass a request along a chain of handlers until one of them handles it.</blockquote><h3>Real-World Usage:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*AYZUe4pc0gdFzMrk28Rx8g.png" /><figcaption>1. Ingredients Enum</figcaption></figure><p>First, let’s start by creating an ingredients enum with different wildflowers. *legend says that these were used for different potions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*GnCZOt8rUoZU5FA9os4Hhw.png" /><figcaption>2. Handler Protocol</figcaption></figure><p>Second, let’s define a Handler protocol with a few things:</p><ul><li>a nextHandler variable</li><li>a handle() method for handling the request</li><li>a setNext() method for setting the next handler</li></ul><p>Also, let’s create some default implementations for the setNext(handler: Handler) &amp; handle(request: Ingredients) methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*VN6ww_ugRkDmrYM69QkMNw.png" /><figcaption>3. Concrete Handlers</figcaption></figure><p>Third, let’s create some concrete handler classes that conform to the Handler protocol. One handler for every ingredient. The premise is simple, the handler checks the request if it corresponds to its ingredient then it’s added to the brew. If it doesn’t correspond, it passes the request to the next handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn0NfdqfzOr3oVYq_DQkHw.png" /><figcaption>4. Cauldron &amp; WitchApp class</figcaption></figure><p>Fourth, let’s define our cauldron class where we put everything together. In the brew() method we pass a list of ingredients and a first handler. The method goes through the list of ingredients and checks if the ingredient is compatible with the handler. If it is compatible then the result is printed if not an appropriate message is displayed.</p><p>Finally, in our WitchApp test() method, we put everything together and as shown, as a first handler we choose the blackthorn with the following next handlers:</p><ul><li>Elder</li><li>Rowan</li><li>May</li></ul><p>Thus creating a chain of handlers or a chain of responsible entities for a particular request.</p><p>When we call the brew() method from the cauldron with that list of ingredients and use the blackthorn as a first handler, the method will go through the entire list, adding the ingredients that have a corresponding handler to the brew. When it reaches the .knotweed element, it will say that it’s not compatible with the brew.</p><p>From this point on, the sky is the limit 🚀 well…almost.</p><p>Of course, this design pattern has its limitations but used in moderation, it’s a great tool in our development toolbox.</p><blockquote><em>This is the next article in the Swift Problems Catalogue series in which I’ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.</em></blockquote><p>Let me know what you think and don’t be shy to share where and when this pattern simplified your coding experience 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=244dcf79e406" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salt-pepper/pass-a-request-along-a-chain-of-handlers-244dcf79e406">Pass a request along a chain of handlers</a> was originally published in <a href="https://medium.com/salt-pepper">salt&amp;pepper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>