<?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 Herlandro Hermogenes on Medium]]></title>
        <description><![CDATA[Stories by Herlandro Hermogenes on Medium]]></description>
        <link>https://medium.com/@herlandro?source=rss-90897b12daf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l7W7Ci3VoU5joJzepVyXDQ.jpeg</url>
            <title>Stories by Herlandro Hermogenes on Medium</title>
            <link>https://medium.com/@herlandro?source=rss-90897b12daf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:41:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@herlandro/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[Um Segredo do #Predicate em Swift: Por Que Uma Linha Muda Tudo?]]></title>
            <link>https://medium.com/@herlandro/um-segredo-do-predicate-em-swift-por-que-uma-linha-muda-tudo-949625808ddb?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/949625808ddb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[predicate]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 09:44:18 GMT</pubDate>
            <atom:updated>2025-12-05T09:44:58.760Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A resposta surpreendente por trás de erros invisíveis nas suas queries SwiftData</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*om5KvXa1T4BJ9zClDVH7xw.png" /></figure><p>Um “predicate” é uma condição booleana usada para selecionar ou filtrar registros. Ele responde “este objeto atende ao critério?” e retorna verdadeiro ou falso.</p><p>Em bancos/ORMs, o predicate é enviado para o mecanismo de persistência, que retorna apenas os registros que satisfazem a condição.</p><p>Já no ecossistema da Apple temos:</p><ul><li>NSPredicate: API clássica (Core Data, Foundation) baseada em strings formatadas, como `NSPredicate(format: “age &gt;= %d”, 18)` . É flexível, mas menos segura (erros só aparecem em runtime).</li><li>#Predicate: DSL moderno e tipado (SwiftData/SwiftUI). Você escreve condições com código Swift e o macro gera uma expressão booleana segura em tempo de compilação.</li></ul><h4><strong>Uso em SwiftData/SwiftUI</strong></h4><p><a href="http://twitter.com/Query">@Query</a>(filter: #Predicate&lt;Model&gt; { … }) , o $0 representa um registro do tipo Model . Você compara campos com valores capturados:</p><pre>// Exemplo com strings: <br>#Predicate&lt;CompanyAndLocation&gt; { <br>  $0.company.name == companyName &amp;&amp; $0.location.location == locationName <br>}<br><br>// Exemplo por identidade:<br>#Predicate&lt;CompanyAndLocation&gt; { <br>  $0.company.id == companyId &amp;&amp; $0.location.id == locationId <br>}<br></pre><p>Isso permite que o filtro rode no store, retornando apenas os itens que batem com o critério.</p><h4><strong>Quando usar o #Predicate?</strong></h4><ul><li>Filtrar uma coleção persistida via <a href="http://twitter.com/Query">@Query</a> ou FetchDescriptor para trazer do banco somente o que importa.</li><li>Substitui NSPredicate quando você quer segurança de tipos e integração direta com SwiftData.</li></ul><h4>Quais são as vantagens do #Predicate?</h4><ul><li>Tipado e checado em compile-time.</li><li>Integra-se ao <a href="http://twitter.com/Query">@Query</a> e FetchDescriptor , reduzindo erros de formatação.</li><li>Melhora completions e refatorações (se você renomear um campo, o compilador ajuda).</li></ul><h4>Cuidado com algumas pequenas armadilhas!?</h4><ul><li>Comparar “key path com key path” em vez de “campo com valor” causa erros de tipo no DSL.</li><li>Referenciar self ou propriedades de <a href="http://twitter.com/Model">@Model</a> dentro do bloco sem capturar valores simples pode quebrar a expansão do macro.</li><li>Comparar relacionamentos por objeto inteiro pode falhar dependendo da versão do SDK; <strong>comparar por id ou por atributos únicos é mais robusto</strong>.</li></ul><h4>Show me the code:</h4><pre>// PredicateApp.swift<br><br>import SwiftUI<br>import SwiftData<br><br>@main<br>struct PredicateApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            DataView(<br>                company: Company(name: &quot;Company 1&quot;, type: 1),<br>                location: Location(location: &quot;Location 1&quot;, value: 100)<br>            )<br>        }<br>    }<br>}</pre><pre>// CompanyAndLocation.swift<br><br>import SwiftData<br>@Model<br>class Company {<br>  #Unique&lt;Company&gt;([\.name])<br>  var name: String<br>  var type: Int<br><br>  init(name: String, type: Int) {<br>    self.name = name<br>    self.type = type<br>  }<br>}<br><br>@Model<br>class Location {<br>  #Unique&lt;Location&gt;([\.location])<br>  var location: String<br>  var value: Int<br>    <br>  init(location: String, value: Int) {<br>    self.location = location<br>    self.value = value<br>  }<br>}<br><br>@Model<br>class CompanyAndLocation {<br>  #Unique&lt;CompanyAndLocation&gt;([\.company, \.location])<br>  var company: Company<br>  var location: Location<br>    <br>  init(company: Company, location: Location) {<br>    self.company = company<br>    self.location = location<br>  }<br>}</pre><pre>// DataView.swift<br><br>import SwiftUI<br>import SwiftData<br><br>struct DataView: View {<br>    <br>    @Environment(\.modelContext) var modelContext<br>    var company: Company<br>    var location: Location<br>    @Query var companyAndLocation: [CompanyAndLocation]<br>    <br>    var body: some View {<br>        Text(&quot;Hello World!&quot;)<br>    }<br>    <br>    init(company: Company, location: Location) {<br>        self.company = company<br>        self.location = location<br>        <br>        let predicate = #Predicate&lt;CompanyAndLocation&gt;<br>        {<br>            $0.company == self.company &amp;&amp; $0.location == self.location<br>        }<br>        <br>        _companyAndLocation = Query(filter: predicate)<br>    }<br>}</pre><p>Crie um projeto SwiftUI, adicione estes 3 arquivos e compile o projeto. E se você este erro significa que está tudo certo (em receber o erro).</p><pre>Cannot convert value of type &#39;PredicateExpressions.Conjunction&lt;PredicateExpressions.<br>Equal&lt;PredicateExpressions.KeyPath&lt;PredicateExpressions.Variable&lt;CompanyAndLocation&gt;, Company&gt;, <br>PredicateExpressions.KeyPath&lt;PredicateExpressions.Value&lt;DataView&gt;, Company&gt;&gt;, <br>PredicateExpressions.Equal&lt;PredicateExpressions.KeyPath&lt;PredicateExpressions.Variable&lt;CompanyAndLocation&gt;, <br>Location&gt;, PredicateExpressions.KeyPath&lt;PredicateExpressions.Value&lt;DataView&gt;, <br>Location&gt;&gt;&gt;&#39; to closure result type &#39;any StandardPredicateExpression&lt;Bool&gt;&#39;</pre><p>Esse erro indica que estamos tentando comparar <strong>objetos complexos</strong> diretamente, quando o #Predicate só aceita comparações de <strong>tipos escalares</strong> (Int, String, UUID, etc.). Também o erro indica que o fechamento de Predicate está retornando um tipo interno do DSL (Conjunction&lt;Equal&lt;…&gt;&gt; ) que não está sendo aceito como any StandardPredicateExpression, normalmente por construção incorreta do predicate (mistura de variável x valor ou uso de key paths em vez de valores).</p><p>O problema está nesta parte do código:</p><pre>let predicate = #Predicate&lt;CompanyAndLocation&gt;<br>{<br>  $0.company == self.company &amp;&amp; $0.location == self.location<br>}</pre><p>Poderíamos resolver assim:</p><pre>let companyName = company.name<br>let locationName = location.location<br>let predicate = #Predicate&lt;CompanyAndLocation&gt; <br>{<br>  $0.company.name == companyName &amp;&amp; $0.location.location == locationName<br>}</pre><p>Se eu não precisasse comparar o objeto completo. Mas e se eu precisasse?Neste caso para 2 propriedades seria simples, mas se este objeto tivesse mais propriedades? E se esse objeto fosse atualizado com mais propriedades com o decorrer do tempo? Então eu teria que voltar nesse código para atualizá-lo e garantir uma comparação completa.</p><p>Podemos tentar assim:</p><pre>let predicate = #Predicate&lt;CompanyAndLocation&gt; {<br>  $0.company.id == company.id &amp;&amp; $0.location.id == location.id<br>}</pre><p>Aqui estamos tentando <strong>acessar</strong> company.id e location.id <strong>diretamente</strong>.<strong> </strong>O macro não consegue rastrear essas propriedades dinâmicas de objetos externos. Ele espera valores simples e escalares que possam ser “capturados” como constantes. Ou seja, <strong>não funciona</strong>.</p><h4><strong>A solução:</strong> Compare os identificadores, não os objetos:</h4><p>Essa é uma questão comum com Swift’s #Predicate macro. O problema está em como o macro captura variáveis. O #Predicate funciona através de <strong>type-safe query generation,</strong> ou seja, precisa traduzir sua expressão Swift para uma query que pode ser executada no banco de dados (CoreData ou SwiftData).</p><p>Então resolvemos assim:</p><pre>let companyId = company.id<br>let locationId = location.id<br>let predicate = #Predicate&lt;CompanyAndLocation&gt; <br>{<br>  $0.company.id == companyId &amp;&amp; $0.location.id == locationId<br>}</pre><ul><li>As variáveis companyId e locationId são <strong>capturadas pelo closure</strong> como valores simples (Equatable)</li><li>O macro consegue identificá-las como constantes externas e substituí-las corretamente na query</li></ul><h4><strong>Conclusão:</strong></h4><p>O #Predicate só consegue traduzir para queries de banco de dados expressões que comparam <strong>valores escalares</strong> (números, strings, UUIDs). Comparações entre objetos complexos não podem ser traduzidas para SQL/query de dados.</p><p>Então dentro de um #Predicate, <strong>compare os identificadores e não os objetos</strong>, <strong>sempre extraia os valores</strong> que você quer comparar em variáveis locais simples <strong>antes</strong> de usá-las no closure. Isso permite que o macro entenda exatamente quais constantes devem ser &quot;compiladas&quot; na query.</p><blockquote><strong>If you’ve enjoyed this article, </strong><a href="https://medium.com/@herlandro/subscribe"><strong>subscribe</strong></a><strong> and get an email as soon as I publish!<em><br></em></strong>Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949625808ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A #Predicate Secret in Swift: Why One Line Changes Everything?]]></title>
            <link>https://medium.com/@herlandro/a-predicate-secret-in-swift-why-one-line-changes-everything-6a1c41c371b7?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1c41c371b7</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[predicate]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 09:41:13 GMT</pubDate>
            <atom:updated>2025-12-05T09:41:43.086Z</atom:updated>
            <content:encoded><![CDATA[<h4>The surprising answer behind invisible errors in your SwiftData queries</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*om5KvXa1T4BJ9zClDVH7xw.png" /></figure><p>A “predicate” is a boolean condition used to select or filter records. It answers “does this object meet the criteria?” and returns true or false.</p><p>In databases/ORMs, the predicate is sent to the persistence engine, which returns only the records that satisfy the condition.</p><p>In the Apple ecosystem, we have:</p><ul><li><strong>NSPredicate:</strong> The classic API (Core Data, Foundation) based on formatted strings, like NSPredicate(format: &quot;age &gt;= %d&quot;, 18). It’s flexible, but less safe (errors only appear at runtime).</li><li><strong>#Predicate:</strong> A modern, type-safe DSL (SwiftData/SwiftUI). You write conditions with Swift code, and the macro generates a compile-time safe boolean expression.</li></ul><h4><strong>Usage in SwiftData/SwiftUI</strong></h4><p>@Query(filter: #Predicate&lt;Model&gt; { ... }), where $0 represents a record of type Model. You compare fields with captured values:</p><pre>// Example with strings: <br>#Predicate&lt;CompanyAndLocation&gt; { <br>  $0.company.name == companyName &amp;&amp; $0.location.location == locationName <br>}<br><br>// Example by identity:<br>#Predicate&lt;CompanyAndLocation&gt; { <br>  $0.company.id == companyId &amp;&amp; $0.location.id == locationId <br>}</pre><p>This allows the filter to run in the store, returning only items that match the criteria.</p><h4><strong>When to use #Predicate?</strong></h4><p>Filter a persisted collection via @Query or FetchDescriptor to bring from the database only what matters.<br>It replaces NSPredicate when you want type safety and direct integration with SwiftData.</p><h4><strong>What are the advantages of #Predicate?</strong></h4><ul><li>Type-checked at compile-time.</li><li>Integrates with @Query and FetchDescriptor, reducing formatting errors.</li><li>Improves completions and refactoring (if you rename a field, the compiler helps).</li></ul><p><strong>Watch out for some small pitfalls!</strong></p><ul><li>Comparing “key path to key path” instead of “field to value” causes type errors in the DSL.</li><li>Referencing self or properties of @Model inside the block without capturing simple values can break macro expansion.</li><li>Comparing relationships by the entire object may fail depending on the SDK version; comparing by id or unique attributes is more robust.</li></ul><p><strong>Show me the code:</strong></p><pre>// PredicateApp.swift<br><br>import SwiftUI<br>import SwiftData<br>@main<br>struct PredicateApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            DataView(<br>                company: Company(name: &quot;Company 1&quot;, type: 1),<br>                location: Location(location: &quot;Location 1&quot;, value: 100)<br>            )<br>        }<br>    }<br>}</pre><pre>// CompanyAndLocation.swift<br><br>import SwiftData<br>@Model<br>class Company {<br>  #Unique&lt;Company&gt;([\.name])<br>  var name: String<br>  var type: Int<br>  init(name: String, type: Int) {<br>    self.name = name<br>    self.type = type<br>  }<br>}<br>@Model<br>class Location {<br>  #Unique&lt;Location&gt;([\.location])<br>  var location: String<br>  var value: Int<br>    <br>  init(location: String, value: Int) {<br>    self.location = location<br>    self.value = value<br>  }<br>}<br>@Model<br>class CompanyAndLocation {<br>  #Unique&lt;CompanyAndLocation&gt;([\.company, \.location])<br>  var company: Company<br>  var location: Location<br>    <br>  init(company: Company, location: Location) {<br>    self.company = company<br>    self.location = location<br>  }<br>}</pre><pre>// DataView.swift<br><br>import SwiftUI<br>import SwiftData<br>struct DataView: View {<br>    <br>    @Environment(\.modelContext) var modelContext<br>    var company: Company<br>    var location: Location<br>    @Query var companyAndLocation: [CompanyAndLocation]<br>    <br>    var body: some View {<br>        Text(&quot;Hello World!&quot;)<br>    }<br>    <br>    init(company: Company, location: Location) {<br>        self.company = company<br>        self.location = location<br>        <br>        let predicate = #Predicate&lt;CompanyAndLocation&gt;<br>        {<br>            $0.company == self.company &amp;&amp; $0.location == self.location<br>        }<br>        <br>        _companyAndLocation = Query(filter: predicate)<br>    }<br>}</pre><p>Create a SwiftUI project, add these 3 files, and build the project. If you get this error, it means you’re on the right track (in receiving the error):</p><pre>Cannot convert value of type &#39;PredicateExpressions.Conjunction&lt;PredicateExpressions.<br>Equal&lt;PredicateExpressions.KeyPath&lt;PredicateExpressions.Variable&lt;CompanyAndLocation&gt;, Company&gt;, <br>PredicateExpressions.KeyPath&lt;PredicateExpressions.Value&lt;DataView&gt;, Company&gt;&gt;, <br>PredicateExpressions.Equal&lt;PredicateExpressions.KeyPath&lt;PredicateExpressions.Variable&lt;CompanyAndLocation&gt;, <br>Location&gt;, PredicateExpressions.KeyPath&lt;PredicateExpressions.Value&lt;DataView&gt;, <br>Location&gt;&gt;&gt;&#39; to closure result type &#39;any StandardPredicateExpression&lt;Bool&gt;&#39;</pre><p>This error means you’re trying to compare complex objects directly, when #Predicate only accepts comparisons of scalar types (Int, String, UUID, etc.). It also means the Predicate closure is returning an internal DSL type (Conjunction&lt;Equal&lt;…&gt;&gt;) that isn’t accepted as any StandardPredicateExpression, usually due to incorrect predicate construction (mixing variable vs value or using key paths instead of values).</p><p>The problem is in this part of the code:</p><pre>let predicate = #Predicate&lt;CompanyAndLocation&gt;<br>{<br>  $0.company == self.company &amp;&amp; $0.location == self.location<br>}</pre><p>You could solve it like this:</p><pre>let companyName = company.name<br>let locationName = location.location<br>let predicate = #Predicate&lt;CompanyAndLocation&gt; <br>{<br>  $0.company.name == companyName &amp;&amp; $0.location.location == locationName<br>}</pre><p>If you don’t need to compare the whole object. But what if you do? For two properties it’s simple, but what if this object had more properties? And what if it gets updated with more properties over time? You’d have to revisit this code to update it and ensure a complete comparison.</p><p>You could try:</p><pre>let predicate = #Predicate&lt;CompanyAndLocation&gt; {<br>  $0.company.id == company.id &amp;&amp; $0.location.id == location.id<br>}</pre><p>Here you’re trying to access company.id and location.id directly. The macro can’t track these dynamic properties of external objects. It expects simple, scalar values that can be captured as constants. In other words, it doesn’t work.</p><h4><strong>The solution: Compare identifiers, not objects:</strong></h4><p>This is a common issue with Swift’s #Predicate macro. The problem is in how the macro captures variables. #Predicate works through type-safe query generation, meaning it needs to translate your Swift expression into a query that can be executed in the database (CoreData or SwiftData).</p><p>So, solve it like this:</p><pre>let companyId = company.id<br>let locationId = location.id<br>let predicate = #Predicate&lt;CompanyAndLocation&gt; <br>{<br>  $0.company.id == companyId &amp;&amp; $0.location.id == locationId<br>}</pre><p>The variables companyId and locationId are captured by the closure as simple (Equatable) values.<br>The macro can identify them as external constants and substitute them correctly in the query.</p><h4><strong>Conclusion:</strong></h4><p>#Predicate can only translate to database queries expressions that compare scalar values (numbers, strings, UUIDs). Comparisons between complex objects cannot be translated to SQL/data queries.</p><p>So, inside a #Predicate, compare identifiers, not objects. Always extract the values you want to compare into simple local variables before using them in the closure. This allows the macro to understand exactly which constants should be compiled into the query.</p><blockquote><strong>If you’ve enjoyed this article, </strong><a href="https://medium.com/@herlandro/subscribe"><strong>subscribe</strong></a><strong> and get an email as soon as I publish!<em><br></em></strong>Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1c41c371b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Boost Function Performance and Achieve Execution Over 10 Million Times Faster]]></title>
            <link>https://medium.com/@herlandro/how-to-make-a-swift-function-10-625-000-times-faster-218808a7c4c2?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/218808a7c4c2</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 20:34:29 GMT</pubDate>
            <atom:updated>2025-08-14T08:51:29.140Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swift | Mathematics | Performance</h4><h4>Discover how a 19th-century mathematical shortcut transformed the performance of a 21st-century gaming algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RvTsL0qnbC_Z3Hiiqt8lg.jpeg" /></figure><blockquote>🫶 <strong>Quick thing before we dive in:</strong> If this article helps you even a little, tapping that 👏 button (you can hit it up to 50 times!) helps it reach more iOS devs. It’s a small gesture that makes a big difference. Thanks!</blockquote><p>As developers, we constantly seek ways to optimize our code. Sometimes, the most powerful optimization come from seemingly simple ideas. Today, I’ll share a fascinating story about Carl Friedrich Gauss, a 19th-century mathematician, and show how his arithmetic shortcut can dramatically improve performance in Swift — both in theoretical and real-world scenarios.</p><p>Buckle up, because in the end of this article, you’ll understand the magic of Gauss’s formula.</p><p>Imagine you need to calculate the sum of all integers from 1 to nnn. It’s a classic problem with several ways to solve it. For demonstration, I wrote three Swift functions:</p><p><strong>1 — For-In Loop</strong><br>This is the most straightforward approach. We iterate through each number from 1 to n and add them up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7082302c0eab6283ea0e83d556e8ff04/href">https://medium.com/media/7082302c0eab6283ea0e83d556e8ff04/href</a></iframe><p><strong>2 — Reduce Method</strong><br>Swift’s functional programming capabilities let us use the reduce method to sum the numbers in a range:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/038e5671af25891843f3c6abacf16aec/href">https://medium.com/media/038e5671af25891843f3c6abacf16aec/href</a></iframe><p><strong>3 — Gauss’s Formula</strong><br>Now, let’s introduce the <strong>star of our show </strong>— Gauss’s formula. As a child, Gauss cleverly discovered that the sum of numbers from 1 to n could be calculated with this simple equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/0*CThgIJHt5TrJo_4-" /></figure><p>Translated to Swift, it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb9601308573ad31c40e9f601d3c5cc/href">https://medium.com/media/bcb9601308573ad31c40e9f601d3c5cc/href</a></iframe><h4>Testing Performance</h4><p>To measure how these methods perform, I used Swift’s DispatchTime API to calculate execution times in nanoseconds. Here’s how the results looked for n = 1,000,000:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a1ca5f33b77e577be0a3de44bd7d311/href">https://medium.com/media/5a1ca5f33b77e577be0a3de44bd7d311/href</a></iframe><h4>Who’s the Fastest?</h4><p>Before we dive into the performance comparison, let’s briefly discuss <strong>Big-O notation</strong> — a fundamental concept in computer science that helps us evaluate an algorithm’s efficiency.</p><p><strong>Big-O notation</strong> describes how the execution time (or space usage) of an algorithm grows relative to the size of the input. It’s expressed in terms of <em>n</em>, where <em>n</em> represents the size of the input data.</p><p>For example:</p><ul><li><strong>O(1)</strong>: Constant time. The algorithm’s performance does not depend on <em>n</em>.</li><li><strong>O(n)</strong>: Linear time. The execution time grows proportionally with <em>n</em>.</li><li><strong>O(n²)</strong>: Quadratic time. The execution time grows exponentially as <em>n</em> increases.</li></ul><p>Understanding Big-O is crucial because it allows us to predict how an algorithm will perform as the input size scales, making it easier to choose the most efficient solution for a given problem.</p><p>Now, back to our comparison. Here’s how the three methods stack up in terms of Big-O:</p><ul><li><strong>For-In Loop</strong>: This approach processes each number individually, resulting in a time complexity of <strong>O(n)</strong>. For large n, the execution time grows linearly.</li><li><strong>Reduce Method</strong>: While it uses functional programming, it also iterates through the range internally, giving it the same <strong>O(n)</strong> complexity as the For-In loop.</li><li><strong>Gauss’s Formula</strong>: This is the clear winner. Thanks to its constant-time complexity <strong>O(1)</strong>, it calculates the sum directly using a single arithmetic operation, regardless of n.</li></ul><p>For n = 1,000,000, this difference is striking. The For-In loop and Reduce method take thousands of nanoseconds, while Gauss’s formula completes in just a fraction of that time.</p><p>By leveraging a smarter algorithm, we achieve not just better performance but also scalability, making Gauss’s formula a go-to solution for summing sequences or similar problems.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a97dd46e1e0deddfdb9a30df37b1aa2f/href">https://medium.com/media/a97dd46e1e0deddfdb9a30df37b1aa2f/href</a></iframe><p>The average execution time:</p><ul><li>Gauss Formula: <strong>16</strong> nanoseconds (0.000000016 seconds)</li><li>Reduce or ForIn: <strong>170.000.000 </strong>nanoseconds (0.17 seconds)</li></ul><p><strong>With Gauss’s formula, the function ran 10,625,000 times faster.</strong></p><h4>Real-World Application: Leaderboard Scores</h4><p>Let’s move from theory to practice. I am building a gaming app where players accumulate scores as they progress through levels. To display a leaderboard, I need to calculate the total score up to a specific level n.</p><p>Here’s how I can solve it using the same three approaches <strong>(deja vu)</strong>:</p><h4>1 — Using a Loop (Naive Approach)</h4><p>Iterates through the scores and sums them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dad4550c47cdba8606690fb6efb18f2c/href">https://medium.com/media/dad4550c47cdba8606690fb6efb18f2c/href</a></iframe><h4>2 — Using Reduce (Functional Approach)</h4><p>Summing scores with Swift’s reduce:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bef1f893800b6f6d30e4a7a59ab226dd/href">https://medium.com/media/bef1f893800b6f6d30e4a7a59ab226dd/href</a></iframe><h4>3 — Using Gauss’s Formula (Optimized)</h4><p>If scores are predictable (like 1, 2, 3, …), we can compute the total directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/298fb6b95f57f1403123faa35b216303/href">https://medium.com/media/298fb6b95f57f1403123faa35b216303/href</a></iframe><h4>Performance Comparison</h4><p>With 1,000,000 levels, the Gauss formula significantly outperforms the loop and reduce methods.</p><h4>Bonus Application: Finding Missing Numbers</h4><p>Here’s another practical use case: detecting a <strong>missing number in a sequence</strong>. Suppose you have a sequence of numbers from 1 to <em>n</em>, but one number is missing. By calculating the expected sum using <strong>Gauss’s formula</strong> and subtracting the actual sum, you can find the missing number instantly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f401e61b4d0610334c2c15ed66a5332/href">https://medium.com/media/8f401e61b4d0610334c2c15ed66a5332/href</a></iframe><p>Let&#39;s test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90cf21fdbd28c41b83c56a376f21d6e3/href">https://medium.com/media/90cf21fdbd28c41b83c56a376f21d6e3/href</a></iframe><h4>The Beauty of Gauss’s Formula</h4><p>This journey from theory to real-world applications reveals <strong>how a centuries-old mathematical insight can optimize modern code</strong>. Gauss’s formula reduces time complexity from <strong>O(n)</strong> to <strong>O(1)</strong>, making it ideal for high-performance apps and large datasets.</p><p>Chances are, a clever trick like this could save you both time and computational resources. Next time you face a computational challenge, ask your self: <strong>Is there a smarter way?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=218808a7c4c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This One Command Lets You Live-Edit UIKit Apps Like It’s SwiftUI]]></title>
            <link>https://medium.com/@herlandro/how-to-update-uikit-project-interfaces-in-real-time-with-lldb-without-swiftui-d51c0d15319e?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d51c0d15319e</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 12:37:47 GMT</pubDate>
            <atom:updated>2025-05-21T15:05:52.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-b9hUhV_a3Yg73uwccI0g.jpeg" /></figure><h4>Discover an advanced technique to modify your iOS app’s appearance in real-time, without recompiling, by harnessing the power of LLDB — perfect for those still working with UIKit.</h4><p>When developing iOS apps, especially when working on UIKit-based projects, there are moments when you need to make small adjustments to the interface while debugging, without restarting the simulator or the app. This can be done effortlessly using LLDB, a powerful debugging tool in Xcode.</p><p>In this guide, I’ll show you how to update the background color of a UIView at runtime using LLDB and the main thread. This technique is especially useful for projects that haven&#39;t yet transitioned to SwiftUI, where dynamic layouts and previews are much easier to handle.</p><h4>The Problem</h4><p>Changing the UI during development often requires recompiling or restarting the simulator, which can be time-consuming. LLDB allows us to make these changes directly in the simulator, speeding up iterations when developing interfaces with UIKit.</p><p>Here’s how you can do it:</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = UIColor.green<br>    }<br>}</pre><h4>2. Setting Up a Breakpoint</h4><ul><li>Run the project in the simulator.</li><li>Set a breakpoint on the line where the background color is defined (`view.backgroundColor = UIColor.green`).</li><li>Xcode will pause the app execution when the breakpoint is hit.</li></ul><h4>3. Using LLDB</h4><p>With the simulator paused at the breakpoint, we can now use LLDB to change the background color of the view directly, without needing to restart the simulator. The key here is to remember that any UI updates need to happen on the main thread.</p><p>In the LLDB console, execute the following command:</p><pre>(lldb) e DispatchQueue.main.async { self.view.backgroundColor = UIColor.blue }</pre><p>This command ensures that the update occurs on the main thread using DispatchQueue.main.async, which prevents common issues with manipulating the UI on background threads.</p><h4>4. Resuming Execution</h4><p>After running the command in LLDB, the background color of the UIView in the simulator will immediately change to blue. You can now resume the app&#39;s execution by pressing the &quot;Continue&quot; button in Xcode or by running the command:</p><pre>(lldb) continue</pre><p>This allows you to quickly iterate through UI changes, testing different colors or visual properties without the need to recompile or restart the app.</p><h4>Extra Tips</h4><ul><li>You can use this method to dynamically change any UI property, such as the text of a UILabel or the image in a UIImageView.</li><li>While LLDB is a powerful tool, keep in mind that changes made this way are temporary and won’t persist once the app is restarted.</li></ul><h4>Conclusion</h4><p>This guide demonstrates how LLDB can be an extremely useful tool for developers working with UIKit, enabling them to debug or modify UI elements at runtime. By using this technique, you can quickly iterate during the development process, saving time and boosting productivity.</p><p>Got more LLDB tips or want to share your own debugging workflow? Drop a comment below and join the conversation!</p><p><strong><em>If you’ve enjoyed this article, </em></strong><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> and get an email as soon as I publish!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d51c0d15319e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to fix the error: DT_TOOLCHAIN_DIR cannot be used to evaluate LIBRARY_SEARCH_PATHS, use…]]></title>
            <link>https://medium.com/@herlandro/how-to-fix-the-error-dt-toolchain-dir-cannot-be-used-to-evaluate-library-search-paths-use-49d3821fd3c7?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/49d3821fd3c7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 21:52:50 GMT</pubDate>
            <atom:updated>2024-10-07T22:01:25.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhoOA44Jwdr2YcBcEaZRBQ.jpeg" /></figure><h3>How to fix the error: DT_TOOLCHAIN_DIR cannot be used to evaluate LIBRARY_SEARCH_PATHS, use TOOLCHAIN_DIR instead</h3><h4>Firebase and Firebase Analytics Pods Error in Xcode 15</h4><p>In Xcode 15, Apple made a modification to the variable that points to the default toolchain location, replacing from $DT_TOOLCHAIN_DIR to $TOOLCHAIN_DIR. If your project or target relies on the previous variable, you should update it to use $TOOLCHAIN_DIR.</p><p>To perform this replacement, you can add the following code snippet at the end of your project’s Podfile. This error was on a MacOS v14 (Sonoma), XCode 15.4, Swift 5.0 regarding the Firebase and Firebase Analytics Pods.</p><h4>Solution:</h4><p>Add this code to your Podfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/400f3519c468f9a8ce31160c7fabd2d9/href">https://medium.com/media/400f3519c468f9a8ce31160c7fabd2d9/href</a></iframe><p>and run</p><pre>pod install</pre><p><em>How many seconds does it take to give 42 claps?<br>If you’ve enjoyed this article, </em><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> </em></strong><em>and get an email as soon as I publish!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49d3821fd3c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create the Carousel UIKit in Swift: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@herlandro/how-to-create-the-carousel-uikit-in-swift-a-step-by-step-guide-64062880fea4?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/64062880fea4</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 21:23:35 GMT</pubDate>
            <atom:updated>2024-10-07T21:28:35.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDVCgmmYDdqxAyDGTCN56w.jpeg" /></figure><h4>The <a href="https://github.com/herlandro/Carousel-UIK">Carousel-UIK</a> project is an example of a user interface component developed in Swift, designed to create a carousel for images or any other visual content.</h4><h4>In this article, we will guide you through the steps to create the Carousel-UIK in Swift.</h4><h4>Step 1: Project Setup</h4><p>Before diving into the coding, we need to set up the project in Xcode.</p><p><strong>Creating the Project</strong>:</p><ul><li>Open Xcode and select “Create a new Xcode project”.</li><li>Choose “App” and click “Next”.</li><li>Name the project, choose the language “Swift,” and set the interface to “Storyboard” or “SwiftUI” (we’ll use Storyboard here).</li><li>Click “Next” and save the project in your desired directory.</li></ul><p><strong>Installing Dependencies (Optional)</strong>:</p><ul><li>If you want to use external libraries like SnapKit to simplify layout management, you can add these dependencies via CocoaPods or Swift Package Manager.</li></ul><h4>Step 2: Structuring the Carousel Component</h4><p>Now, let’s create the basic carousel component.</p><p><strong>Creating the Carousel View</strong>:</p><ul><li>Create a new Swift file called CarouselView.swift.</li><li>Import UIKit: import UIKit.</li><li>Create a CarouselView class that inherits from UIView.</li></ul><pre>import UIKit<br><br>class CarouselView: UIView {<br><br>    // Array of views to be displayed in the carousel<br>    private var itemViews: [UIView] = []<br><br>    // Scroll view to enable horizontal scrolling<br>    private let scrollView: UIScrollView = {<br>        let scrollView = UIScrollView()<br>        scrollView.isPagingEnabled = true<br>        scrollView.showsHorizontalScrollIndicator = false<br>        return scrollView<br>    }()<br><br>    // Initializer for the view<br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        setupView()<br>    }<br><br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        setupView()<br>    }<br><br>    // Initial setup of the view<br>    private func setupView() {<br>        addSubview(scrollView)<br>        scrollView.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            scrollView.leadingAnchor.constraint(equalTo: leadingAnchor),<br>            scrollView.trailingAnchor.constraint(equalTo: trailingAnchor),<br>            scrollView.topAnchor.constraint(equalTo: topAnchor),<br>            scrollView.bottomAnchor.constraint(equalTo: bottomAnchor)<br>        ])<br>    }<br><br>    // Method to add views to the carousel<br>    func setItems(_ views: [UIView]) {<br>        itemViews.forEach { $0.removeFromSuperview() } // Remove previous views<br>        itemViews = views<br>        setupItems()<br>    }<br><br>    // Setup and position the views within the scroll view<br>    private func setupItems() {<br>        var previousView: UIView? = nil<br><br>        for view in itemViews {<br>            scrollView.addSubview(view)<br>            view.translatesAutoresizingMaskIntoConstraints = false<br>            NSLayoutConstraint.activate([<br>                view.topAnchor.constraint(equalTo: scrollView.topAnchor),<br>                view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),<br>                view.widthAnchor.constraint(equalTo: widthAnchor)<br>            ])<br><br>            if let previous = previousView {<br>                view.leadingAnchor.constraint(equalTo: previous.trailingAnchor).isActive = true<br>            } else {<br>                view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true<br>            }<br><br>            previousView = view<br>        }<br><br>        if let lastView = previousView {<br>            lastView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true<br>        }<br>    }<br>}</pre><p>This code creates a CarouselView that manages an array of UIView objects to display within a UIScrollView, enabling horizontal scrolling.</p><h4>Step 3: Configuring the Carousel Items</h4><p>Now that we have the CarouselView, we need to create and add the items to be displayed in the carousel.</p><p><strong>Creating the Items</strong>:</p><ul><li>You can create the carousel items as UIView or UIImageView, depending on the content you want to display.</li></ul><pre>func createCarouselItems() -&gt; [UIView] {<br>    var items: [UIView] = []<br><br>    for i in 1...5 {<br>        let view = UIView()<br>        view.backgroundColor = i % 2 == 0 ? .blue : .red<br>        let label = UILabel()<br>        label.text = &quot;Item \(i)&quot;<br>        label.textColor = .white<br>        label.font = UIFont.boldSystemFont(ofSize: 24)<br>        label.translatesAutoresizingMaskIntoConstraints = false<br>        view.addSubview(label)<br>        NSLayoutConstraint.activate([<br>            label.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            label.centerYAnchor.constraint(equalTo: view.centerYAnchor)<br>        ])<br>        items.append(view)<br>    }<br><br>    return items<br>}</pre><p>In this example, each item is a UIView with alternating background colors and a label centered in it.</p><p><strong>Adding Items to the Carousel</strong>:</p><p>In the main ViewController, add the CarouselView and configure the items</p><pre>override func viewDidLoad() {<br>    super.viewDidLoad()<br><br>    let carouselView = CarouselView()<br>    carouselView.translatesAutoresizingMaskIntoConstraints = false<br>    view.addSubview(carouselView)<br>    NSLayoutConstraint.activate([<br>        carouselView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>        carouselView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>        carouselView.heightAnchor.constraint(equalToConstant: 200),<br>        carouselView.centerYAnchor.constraint(equalTo: view.centerYAnchor)<br>    ])<br><br>    let items = createCarouselItems()<br>    carouselView.setItems(items)<br>}</pre><ol><li>This code adds the CarouselView to the center of the screen and sets the carousel&#39;s height to 200 points.</li></ol><h4>Step 4: Customization and Enhancements</h4><p>Now that we have a basic working carousel, you can customize and enhance it:</p><p><strong>Adding Page Indicators</strong>:</p><p>Add a UIPageControl to indicate the current page.</p><pre>private let pageControl: UIPageControl = {<br>    let pageControl = UIPageControl()<br>    pageControl.currentPageIndicatorTintColor = .black<br>    pageControl.pageIndicatorTintColor = .lightGray<br>    return pageControl<br>}()</pre><p>Then, update the current page as the user scrolls.</p><p><strong>Adding Animations</strong>:</p><p>You can add transition animations between items or even configure auto-scroll so that the carousel automatically changes after a few seconds.</p><p><strong>Customizing the Layout</strong>:</p><p>Use UICollectionView instead of UIScrollView for more layout flexibility and support for behaviors like zooming or different item sizes.</p><h4>Conclusion</h4><p>In this article, we built a basic carousel in Swift using UIKit. We learned how to set up the project, create the CarouselView, add items, and customize the carousel. With this foundation, you can expand the component to meet the specific needs of your application by adding animations, page indicators, and more.</p><p>Explore and modify the code as needed to create a unique and interactive user experience! Get the source-code <a href="https://github.com/herlandro/Carousel-UIK"><strong>here</strong></a></p><p><strong><em>Did you know the clap counter goes up to 42?</em></strong><em><br></em><strong><em>If you’ve enjoyed this article, </em></strong><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> and get an email as soon as I publish!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64062880fea4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 iOS YouTube Channels you should subscribe in 2025]]></title>
            <link>https://medium.com/@herlandro/top-10-youtube-channels-every-ios-developer-should-subscribe-in-2024-f82b13af137d?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f82b13af137d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 05:08:22 GMT</pubDate>
            <atom:updated>2025-05-21T16:05:04.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6EeegljFVKP91LRf4BRTQ.jpeg" /></figure><h4>Staying updated with the latest tools and trends is crucial for iOS developers.</h4><p>Whether you’re a beginner or an expert, YouTube offers a wealth of tutorials and insights. Here’s a curated list of the top 10 channels every iOS developer should follow in 2024 to sharpen their skills and stay on top of the iOS ecosystem.</p><h4><a href="https://www.youtube.com/c/CodeWithChris">1. CodeWithChris</a></h4><p>Beginners learning the fundamentals of iOS development.<strong><br>Notable Series: </strong>iOS Foundations, Build Your First App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvnwOyc9CwCDfF4VnEtWVg.png" /></figure><p>Chris excels at breaking down complex topics into digestible lessons. His content is always beginner-friendly, but he also offers intermediate and advanced tutorials, making this a well-rounded channel.</p><h4><a href="https://www.youtube.com/c/LetsBuildThatApp">2. Lets Build Than App</a></h4><p>Developers seeking practical, hands-on projects.<br><strong>Notable Projects:</strong> Instagram, YouTube Clone, Tinder Clone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3qCxyJM_TlKwcyPKlavKg.png" /></figure><p>With his strong focus on practical app-building, Brian’s tutorials are perfect for those who want to see how theory translates into real-world projects.</p><h4><a href="https://www.youtube.com/c/SeanAllen">3. Sean Allen</a></h4><p>Intermediate and advanced developers looking to level up.<br><strong>Notable Series:</strong> “Swift News,” “iOS Dev Vlog,” “Swift Interview Questions”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wejZghGjFDTlE6Jw-swKtg.png" /></figure><p>Sean’s channel is a goldmine for intermediate developers. He also provides invaluable advice for navigating a career as an iOS developer, including tips on landing a job and becoming a better coder.</p><h4><a href="https://www.youtube.com/c/PaulHudson">4. Paul Hudson</a></h4><p>Comprehensive Swift tutorials for all skill levels.<br><strong>Notable Series:</strong> “100 Days of Swift,” “SwiftUI Projects,” “What’s New in Swift”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrvYrGWJEGkByH0EWhkSIQ.png" /></figure><p>Paul is an authoritative voice in the iOS development community, and his tutorials are extremely well-organized and easy to follow. Whether you’re looking to master SwiftUI or just keep up with the latest changes in Swift, Paul’s channel has you covered.</p><h4><a href="https://www.youtube.com/c/Kavsoft">5. Kavsoft</a></h4><p>Developers focused on SwiftUI and design-centric apps.<br><strong>Notable Projects:</strong> “SwiftUI Animations,” “Custom UI Components”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6xsygJRMfmd6dqIdzC5zQ.png" /></figure><p>If you’re keen on mastering SwiftUI and creating eye-catching, user-friendly apps, Kavsoft is the place to go. The tutorials focus on design as much as development, making this an ideal resource for those looking to craft visually compelling apps.</p><h4><a href="https://www.youtube.com/c/EssentialDeveloper">6. Essential Developer</a></h4><p>Developers interested in clean code, test-driven development, and architectural patterns.<br><strong>Notable Series:</strong> “TDD iOS Series,” “iOS Architecture Patterns”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XcdZXq1tuzwLxF9BqNSskA.png" /></figure><p>If you’re interested in writing cleaner code and learning advanced architecture techniques, Essential Developer will take your skills to the next level. Their content is geared towards more experienced developers but is invaluable for anyone looking to grow professionally.</p><h4><a href="https://www.youtube.com/c/StewartLynch">7. Stewart Lynch</a></h4><p>Developers seeking practical app-building tutorials with an emphasis on educational apps.<br><strong>Notable Projects:</strong> “Build a Core Data App,” “iOS App Development with SwiftUI”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWszsJRTSraDXStxa7ujdg.png" /></figure><p>Stewart’s calm and methodical teaching style is great for developers of all levels. His tutorials are well-organized and cover useful app-building techniques, especially for creating apps with complex data handling.</p><h4><a href="https://www.youtube.com/c/iOSConfSG">8. iOS Conf SG</a></h4><p>Insights from industry experts and conference-level talks.<br><strong>Notable Content:</strong> “iOS Conference Keynotes,” “Expert Workshops”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udU6npcvkIeuudOAjHjChw.png" /></figure><p>This channel provides a rare opportunity to watch high-quality presentations from iOS thought leaders. If you’re looking for deep dives into niche topics and advanced insights, iOS Conf SG delivers.</p><h4><a href="https://www.youtube.com/c/DarrellRoot">9. Darrell Root</a></h4><p>Developers who want to learn SwiftUI through concise, focused tutorials.<br><strong>Notable Series:</strong> “SwiftUI for Beginners,” “SwiftUI App Projects”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeY1IIlIAsCmSyHKe6NgWg.png" /></figure><p>Darrell’s to-the-point tutorials help you get up and running quickly with SwiftUI. If you need to learn a specific technique fast, his channel is a great resource.</p><h4><a href="https://www.youtube.com/@DesignCodeTeam">10. DesignCode</a></h4><p>Developers who want to bridge the gap between development and design.<br><strong>Notable Series:</strong> “SwiftUI for Designers,” “UI/UX Design for Developers”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPsGJ4HRSTK5aAF6_W94Hg.png" /></figure><p>If you want to create apps that not only function well but also look great, DesignCode provides the perfect blend of design and development. It’s particularly useful for developers looking to improve their UI/UX skills.</p><p>Whether you’re a seasoned iOS developer or just starting out, these YouTube channels offer a wealth of resources to help you grow in 2024. From beginner-friendly tutorials to deep dives into advanced topics, you’ll find content tailored to your needs. Subscribing to these channels will ensure you stay updated with the latest trends, tools, and techniques in iOS development.</p><p><strong>Which channel is your favorite, or do you have other recommendations? Let me know in the comments!</strong></p><p>Did you know the clap counter goes up to 30?</p><p>If you found this list helpful, don’t forget to<strong><em> </em></strong><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> </em>to these channels and share this article with your developer friends.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f82b13af137d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 iOS Libraries You Should Replace Before 2025]]></title>
            <link>https://medium.com/@herlandro/10-ios-libraries-you-need-to-replace-in-2024-to-stay-ahead-9ed6a11a0618?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ed6a11a0618</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 19:27:59 GMT</pubDate>
            <atom:updated>2024-10-19T08:14:20.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiXmRXgLDdBPdEAnVQgxZA.jpeg" /></figure><h4>Transform Your Apps by Embracing SwiftUI and Modern Development Practices Today</h4><p>In my previous article, I wrote about the <a href="https://medium.com/@herlandro/top-10-open-source-ios-libraries-every-developer-should-know-in-2024-b6df44555cca">Top 10 open source iOS libraries that every developer should have known before 2024</a></p><p>The technology evolves, so must we. Let me share with you the journey of replacing these 10 legacy libraries with cutting-edge solutions that have revitalized my development process.</p><h3>1. <strong>Alamofire ➡️ URLSession with async/await</strong></h3><p>Letting Go of Alamofire</p><p>I used to swear by Alamofire for all my networking needs. It simplified HTTP requests and made handling responses a breeze. But with the introduction of Swift’s async/await and the powerful capabilities of URLSession, I&#39;ve found that I can achieve the same results with cleaner, more efficient code. Embracing URLSession has reduced dependencies and made my networking layer feel more native and integrated.</p><h3>2. <strong>RxSwift (UIKit) ➡️ Combine</strong></h3><p>Moving Beyond RxSwift to Combine</p><p>RxSwift opened my eyes to the possibilities of reactive programming. However, integrating it with SwiftUI felt like forcing two puzzle pieces that didn’t quite fit. Transitioning to Combine, Apple’s native reactive framework, has been a revelation. The seamless integration with SwiftUI has made my codebase more cohesive and has significantly reduced complexity.</p><h3>3. <strong>Realm ➡️ Core Data with SwiftUI</strong></h3><p>Replacing Realm with Core Data and SwiftUI</p><p>Realm was my trusted companion for data persistence. Its simplicity and performance were unmatched — until SwiftUI enhanced its integration with Core Data. With features like @FetchRequest and better managedObjectContext support, Core Data has become more approachable and efficient. Making the switch has unified my data management and improved app stability.</p><h3>4. <strong>SDWebImage ➡️ AsyncImage or Nuke</strong></h3><p>Evolving from SDWebImage to AsyncImage and Nuke</p><p>Loading images asynchronously was a challenge that SDWebImage elegantly solved. But with SwiftUI’s AsyncImage component introduced in iOS 15, I&#39;ve found a native solution that fits perfectly into my apps. For those times when I need more advanced image processing, Nuke has been a fantastic library that offers SwiftUI support and powerful features.</p><h3>5. <strong>Kingfisher ➡️ Kingfisher for SwiftUI</strong></h3><p>Upgrading Kingfisher for SwiftUI</p><p>Kingfisher has been a staple for image downloading and caching. The good news is that it’s kept up with the times. Its latest versions fully support SwiftUI, making the integration smoother than ever. Continuing with Kingfisher feels like working with an old friend who’s learned new tricks — it’s familiar yet refreshingly modern.</p><h3>6. <strong>Lottie ➡️ Lottie for SwiftUI</strong></h3><p>Enhancing Animations with Lottie in SwiftUI</p><p>Animations add that magical touch to our apps, and Lottie has been instrumental in bringing animations to life. Now that Lottie supports SwiftUI, incorporating those delightful animations has become even more seamless. It’s reignited my passion for creating engaging user experiences.</p><h3>7. <strong>SwiftyJSON ➡️ Codable</strong></h3><p>Embracing Codable over SwiftyJSON</p><p>SwiftyJSON was once my go-to for parsing JSON data. It simplified a complex process and saved me countless hours. But with Swift’s native Codable protocol, I&#39;ve discovered a more streamlined and type-safe way to handle JSON. This shift has made my networking code cleaner and more reliable.</p><h3>8. <strong>Charts ➡️ Apple Charts </strong>Framework</h3><p>Utilizing Apple’s Native Charts Framework</p><p>Creating visually appealing charts was a daunting task that often required bulky third-party libraries. With Apple’s introduction of the native Charts framework, building data visualizations has become an integrated and enjoyable part of development. It’s allowed me to present data in engaging ways without the overhead of external dependencies.</p><h3>9. <strong>SnapKit ➡️ </strong>SwiftUI’s Layout System</h3><p>Transitioning from SnapKit to SwiftUI’s Layout System</p><p>SnapKit made Auto Layout less of a headache, and I was grateful for it. However, SwiftUI’s declarative layout approach has revolutionized how I design interfaces. Using stacks and alignment guides, I’ve been able to create complex layouts with less code and greater flexibility. It’s made UI development a joy again.</p><h3>10. <strong>MBProgressHUD ➡️ ProgressView</strong></h3><p>Modernizing with ProgressView over MBProgressHUD</p><p>MBProgressHUD was the standard for indicating progress and loading states. But SwiftUI’s ProgressView has provided a native, customizable alternative that fits naturally within my apps. It&#39;s simplified my code and enhanced the user experience by providing smooth and responsive feedback.</p><h3>Looking Ahead: The Future of iOS Development</h3><p>Making these changes hasn’t just updated my projects — it’s revitalized my passion for development. Here’s what I see on the horizon:</p><ul><li><strong>SwiftUI Becoming the Norm:</strong> By the end of 2025, I anticipate that SwiftUI will be the foundation of most new iOS projects.</li><li><strong>Reduced Reliance on External Libraries:</strong> As native solutions continue to improve, the need for third-party libraries will diminish, leading to more stable and maintainable codebases.</li><li><strong>Adoption of Native Reactive Programming:</strong> Combine will likely become the standard for reactive programming in Swift, offering seamless integration and performance benefits.</li></ul><p>What about you? Have you started transitioning away from these legacy libraries? I’d love to hear your experiences, challenges, or any tips you might have. Let’s start a conversation and help each other grow in this ever-evolving field!</p><p><strong><em>Did you know the clap counter goes up to 42?</em></strong><em><br></em><strong><em>If you’ve enjoyed this article, </em></strong><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> and get an email as soon as I publish!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ed6a11a0618" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Programming in UIKit — Complete Guide]]></title>
            <link>https://medium.com/@herlandro/reactive-programming-in-uikit-3261e15f3a3e?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3261e15f3a3e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 12:29:47 GMT</pubDate>
            <atom:updated>2024-09-22T16:29:43.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sh7Z5eZZDBHFfboS0YIUQw.jpeg" /></figure><h4>Explore the key differences between traditional, RxSwift, and Combine approaches to iOS development and find out which one is best for your project</h4><p>Reactive programming has become a key approach in the development of modern applications, particularly when dealing with asynchronous data flows and dynamic interfaces. In 2024, its usage is becoming increasingly relevant for both building projects from scratch and maintaining legacy systems that already use frameworks like <strong>RxSwift</strong> or <strong>Combine</strong>.</p><p>In this article, we’ll explore what reactive programming is, why it’s important, and how you can implement it in your <strong>UIKit</strong> projects. Additionally, we’ll walk through a practical example of comparing traditional approaches with reactive programming using <strong>RxSwift</strong> and <strong>Combine</strong>, measuring their performance and efficiency in real-time.</p><h4>What is Reactive Programming?</h4><p>Reactive programming allows your app to <strong>react</strong> to data flows and events in a declarative way. Instead of constantly checking the state of different parts of your interface or data, the system automatically manages updates, reacting to events in an efficient and predictable way.</p><p>In UIKit, this can be extremely useful when handling tasks such as UI updates, network calls, or user interactions, especially when these are asynchronous.</p><h4>Why is Reactive Programming Important?</h4><ol><li><strong>Asynchronous event management</strong>: Many operations in apps are asynchronous (network requests, animations, button clicks), and reactive programming makes handling these data flows more organized.</li><li><strong>Scalability</strong>: In large projects, without reactive programming, the code handling events and states can become messy, with many callbacks and closures. Reactive programming abstracts this complexity and offers a cleaner way to manage it.</li><li><strong>Improved performance</strong>: When combined with UIKit, frameworks like RxSwift and Combine ensure that events and UI changes are propagated efficiently, optimizing the app’s performance.</li></ol><h4>Key Concepts to Study for Reactive Programming in UIKit</h4><p>Before jumping into practical examples, it’s crucial to understand some key concepts:</p><ol><li><strong>Bindings</strong>: How to connect reactive data sources to the UI.</li><li><strong>Observable vs Publisher</strong>: Understanding observables in RxSwift and publishers in Combine.</li><li><strong>Reactive Operators</strong>: Operators like map, filter, flatMap and how they transform and combine data flows.</li><li><strong>Lifecycle Management</strong>: Using DisposeBag (RxSwift) and AnyCancellable (Combine) to manage memory and avoid leaks.</li><li><strong>UI Event Observing</strong>: How to connect UIKit controls, such as buttons, tables, and text fields, to reactive event flows.</li></ol><h3>Practical Example: UI Update with API Call</h3><p>Let’s implement a simple search functionality that fetches user data from an API using three different approaches: traditional callbacks, RxSwift, and Combine. This allows us to see the differences in terms of performance and simplicity.</p><h4>Non-Reactive Approach (UIKit using View Code)</h4><p>Below is a traditional implementation where we manually manage user input events and network responses using callbacks.</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br>    private let searchTextField: UITextField = {<br>        let textField = UITextField()<br>        textField.placeholder = &quot;Search users&quot;<br>        textField.borderStyle = .roundedRect<br>        return textField<br>    }()<br><br>    private let tableView: UITableView = {<br>        let tableView = UITableView()<br>        return tableView<br>    }()<br><br>    var data = [String]() // Simulated API response data<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br><br>        searchTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)<br>    }<br><br>    private func setupViews() {<br>        view.addSubview(searchTextField)<br>        view.addSubview(tableView)<br>        <br>        searchTextField.translatesAutoresizingMaskIntoConstraints = false<br>        tableView.translatesAutoresizingMaskIntoConstraints = false<br>        <br>        NSLayoutConstraint.activate([<br>            searchTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),<br>            searchTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),<br>            searchTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),<br>            <br>            tableView.topAnchor.constraint(equalTo: searchTextField.bottomAnchor, constant: 16),<br>            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)<br>        ])<br>    }<br><br>    @objc func textFieldDidChange(_ textField: UITextField) {<br>        guard let query = textField.text, !query.isEmpty else { return }<br>        searchUsers(query: query) { [weak self] users in<br>            self?.data = users<br>            self?.tableView.reloadData()<br>        }<br>    }<br><br>    func searchUsers(query: String, completion: @escaping ([String]) -&gt; Void) {<br>        // Simulated API call<br>        DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>            let results = [&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;] // Simulated response<br>            completion(results)<br>        }<br>    }<br>}</pre><p><strong>Problems with This Approach:</strong></p><ul><li>You manually handle events and UI updates.</li><li>Callbacks make the code harder to scale and maintain.</li><li>As complexity increases, the code becomes more prone to bugs and difficult to debug.</li></ul><h4>Solution with RxSwift (UIKit using View Code)</h4><p>Now, let’s rewrite the same example using RxSwift to leverage reactive programming.</p><pre>import RxSwift<br>import RxCocoa<br><br>class ViewController: UIViewController {<br>    private let searchTextField: UITextField = {<br>        let textField = UITextField()<br>        textField.placeholder = &quot;Search users&quot;<br>        textField.borderStyle = .roundedRect<br>        return textField<br>    }()<br><br>    private let tableView: UITableView = {<br>        let tableView = UITableView()<br>        return tableView<br>    }()<br><br>    let disposeBag = DisposeBag()<br>    var data = [String]()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br><br>        // Reactive programming to observe text field input<br>        searchTextField.rx.text.orEmpty<br>            .debounce(.milliseconds(300), scheduler: MainScheduler.instance)<br>            .distinctUntilChanged()<br>            .flatMapLatest { query in<br>                self.searchUsers(query: query)<br>            }<br>            .observe(on: MainScheduler.instance)<br>            .subscribe(onNext: { [weak self] users in<br>                self?.data = users<br>                self?.tableView.reloadData()<br>            })<br>            .disposed(by: disposeBag)<br>    }<br><br>    private func setupViews() {<br>        view.addSubview(searchTextField)<br>        view.addSubview(tableView)<br><br>        searchTextField.translatesAutoresizingMaskIntoConstraints = false<br>        tableView.translatesAutoresizingMaskIntoConstraints = false<br><br>        NSLayoutConstraint.activate([<br>            searchTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),<br>            searchTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),<br>            searchTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),<br><br>            tableView.topAnchor.constraint(equalTo: searchTextField.bottomAnchor, constant: 16),<br>            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)<br>        ])<br>    }<br><br>    func searchUsers(query: String) -&gt; Observable&lt;[String]&gt; {<br>        return Observable.create { observer in<br>            DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>                let results = [&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;]<br>                observer.onNext(results)<br>                observer.onCompleted()<br>            }<br>            return Disposables.create()<br>        }<br>    }<br>}</pre><p><strong>Improvements with RxSwift:</strong></p><ul><li>The flow of events is much cleaner and more organized.</li><li>Less manual code and fewer nested callbacks.</li><li>Operators like debounce help optimize performance by avoiding repeated searches while the user types.</li></ul><h4>Solution with Combine (UIKit using View Code)</h4><p>Now let’s implement the same functionality using Combine.</p><pre>import Combine<br><br>class ViewController: UIViewController {<br>    private let searchTextField: UITextField = {<br>        let textField = UITextField()<br>        textField.placeholder = &quot;Search users&quot;<br>        textField.borderStyle = .roundedRect<br>        return textField<br>    }()<br><br>    private let tableView: UITableView = {<br>        let tableView = UITableView()<br>        return tableView<br>    }()<br><br>    var data = [String]()<br>    var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br><br>        NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification, object: searchTextField)<br>            .compactMap { ($0.object as? UITextField)?.text }<br>            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)<br>            .removeDuplicates()<br>            .flatMap { query in<br>                self.searchUsers(query: query)<br>            }<br>            .receive(on: DispatchQueue.main)<br>            .sink { [weak self] users in<br>                self?.data = users<br>                self?.tableView.reloadData()<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br><br>    private func setupViews() {<br>        view.addSubview(searchTextField)<br>        view.addSubview(tableView)<br><br>        searchTextField.translatesAutoresizingMaskIntoConstraints = false<br>        tableView.translatesAutoresizingMaskIntoConstraints = false<br><br>        NSLayoutConstraint.activate([<br>            searchTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),<br>            searchTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),<br>            searchTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),<br><br>            tableView.topAnchor.constraint(equalTo: searchTextField.bottomAnchor, constant: 16),<br>            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)<br>        ])<br>    }<br><br>    func searchUsers(query: String) -&gt; AnyPublisher&lt;[String], Never&gt; {<br>        return Future&lt;[String], Never&gt; { promise in<br>            DispatchQueue.global().asyncAfter(deadline: .now() + 1) {<br>                let results = [&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;]<br>                promise(.success(results))<br>            }<br>        }<br>        .eraseToAnyPublisher()<br>    }<br>}</pre><h4>Improvements with Combine:</h4><ul><li>Simplified syntax, especially with native UIKit integration through NotificationCenter.</li><li>Lifecycle management for publishers is handled efficiently with store(in:).</li><li>Great integration with modern Swift features, making it ideal for new projects.</li></ul><h3>When to Use Reactive Programming in UIKit</h3><ul><li><strong>New Projects</strong>: If your project is new and you want to build something scalable and easy to maintain, both RxSwift and Combine are great options for managing asynchronous events.</li><li><strong>Legacy Projects</strong>: For existing UIKit apps, it’s essential to evaluate if your team is already familiar with RxSwift. In this case, RxSwift may be the safer choice, but Combine offers a more modern and integrated approach, especially if you plan to migrate to SwiftUI in the future.</li></ul><h3>Project: Comparing Traditional, RxSwift, and Combine Approaches in UIKit</h3><h4>Introduction</h4><p>In this project, we’ll implement three different versions of a search feature that fetches data from a fictional API. We’ll use three different programming approaches in parallel to compare:</p><ol><li><strong>Without Reactive Programming</strong> (traditional callbacks)</li><li><strong>With RxSwift</strong> (reactive programming with RxSwift)</li><li><strong>With Combine</strong> (reactive programming with Combine)</li></ol><p>We’ll also set up logs to measure the execution time and performance of each approach in real-time.</p><h4>1. Setting Up the Project in Xcode</h4><ol><li>Open Xcode and create a new <strong>Single View App</strong>.</li><li>Name the project <strong>ReactiveProgrammingComparison</strong>.</li><li>Choose <strong>Swift</strong> as the language and <strong>UIKit</strong> as the interface.</li><li>Ensure “Use Core Data” and “Include Tests” are unchecked.</li></ol><h4>2. Installing RxSwift Dependencies</h4><ul><li><strong>RxSwift</strong>: Use CocoaPods or Swift Package Manager to install RxSwift in the project.</li><li>Using <strong>CocoaPods</strong>, add the following to your Podfile:</li></ul><pre>pod &#39;RxSwift&#39;, &#39;6.0&#39;<br>pod &#39;RxCocoa&#39;, &#39;6.0&#39;</pre><ul><li>Using <strong>Swift Package Manager</strong>:</li></ul><ol><li>In Xcode, go to <strong>File &gt; Swift Packages &gt; Add Package Dependency</strong>.</li><li>Add the URL: <a href="https://github.com/ReactiveX/RxSwift.git.">https://github.com/ReactiveX/RxSwift.git.</a></li></ol><ul><li><strong>Combine</strong> is native to Swift, so no installation is required.</li></ul><h4>3. Implementing the UI Layout with UIKit</h4><p>We’ll create a simple layout divided into three sections. Each section will display the result of the search according to the programming approach used.</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br>    <br>    // Labels to display search results and response times<br>    private let traditionalLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;Traditional:&quot;<br>        label.font = UIFont.systemFont(ofSize: 18)<br>        return label<br>    }()<br>    <br>    private let rxSwiftLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;RxSwift:&quot;<br>        label.font = UIFont.systemFont(ofSize: 18)<br>        return label<br>    }()<br>    <br>    private let combineLabel: UILabel = {<br>        let label = UILabel()<br>        label.text = &quot;Combine:&quot;<br>        label.font = UIFont.systemFont(ofSize: 18)<br>        return label<br>    }()<br>    <br>    // Button to trigger the data fetch<br>    private let fetchButton: UIButton = {<br>        let button = UIButton(type: .system)<br>        button.setTitle(&quot;Fetch Data&quot;, for: .normal)<br>        button.addTarget(self, action: #selector(fetchData), for: .touchUpInside)<br>        return button<br>    }()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupViews()<br>    }<br>    <br>    private func setupViews() {<br>        view.addSubview(traditionalLabel)<br>        view.addSubview(rxSwiftLabel)<br>        view.addSubview(combineLabel)<br>        view.addSubview(fetchButton)<br>        <br>        traditionalLabel.translatesAutoresizingMaskIntoConstraints = false<br>        rxSwiftLabel.translatesAutoresizingMaskIntoConstraints = false<br>        combineLabel.translatesAutoresizingMaskIntoConstraints = false<br>        fetchButton.translatesAutoresizingMaskIntoConstraints = false<br>        <br>        NSLayoutConstraint.activate([<br>            traditionalLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),<br>            traditionalLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            <br>            rxSwiftLabel.topAnchor.constraint(equalTo: traditionalLabel.bottomAnchor, constant: 20),<br>            rxSwiftLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            <br>            combineLabel.topAnchor.constraint(equalTo: rxSwiftLabel.bottomAnchor, constant: 20),<br>            combineLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            <br>            fetchButton.topAnchor.constraint(equalTo: combineLabel.bottomAnchor, constant: 40),<br>            fetchButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)<br>        ])<br>    }<br>    <br>    @objc private func fetchData() {<br>        // Trigger all 3 approaches simultaneously<br>        fetchDataTraditionally()<br>        fetchDataRxSwift()<br>        fetchDataCombine()<br>    }<br>}</pre><h4>4. Implementing the Traditional Callback Approach</h4><pre>func fetchDataTraditionally() {<br>    let startTime = Date()<br>    <br>    // Simulating an API call with delay<br>    DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {<br>        let fetchedData = [&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;]<br>        <br>        DispatchQueue.main.async {<br>            let timeElapsed = Date().timeIntervalSince(startTime)<br>            self.traditionalLabel.text = &quot;Traditional: \(fetchedData) (\(timeElapsed) sec)&quot;<br>        }<br>    }<br>}</pre><p>In this traditional approach, we manually manage the events and measure the execution time using Date().</p><p>5. Implementing the RxSwift Approach</p><pre>import RxSwift<br><br>func fetchDataRxSwift() {<br>    let startTime = Date()<br>    let disposeBag = DisposeBag()<br><br>    Observable.just([&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;])<br>        .delay(.seconds(2), scheduler: MainScheduler.instance)<br>        .subscribe(onNext: { [weak self] fetchedData in<br>            let timeElapsed = Date().timeIntervalSince(startTime)<br>            self?.rxSwiftLabel.text = &quot;RxSwift: \(fetchedData) (\(timeElapsed) sec)&quot;<br>        })<br>        .disposed(by: disposeBag)<br>}</pre><p>In the RxSwift implementation, we simulate the API response using Observable.just and delay it by 2 seconds. The time taken for execution is then displayed.</p><p>6. Implementing the Combine Approach</p><pre>import Combine<br><br>func fetchDataCombine() {<br>    let startTime = Date()<br>    var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    Just([&quot;User1&quot;, &quot;User2&quot;, &quot;User3&quot;])<br>        .delay(for: .seconds(1.8), scheduler: DispatchQueue.main)<br>        .sink(receiveCompletion: { _ in }, receiveValue: { [weak self] fetchedData in<br>            let timeElapsed = Date().timeIntervalSince(startTime)<br>            self?.combineLabel.text = &quot;Combine: \(fetchedData) (\(timeElapsed) sec)&quot;<br>        })<br>        .store(in: &amp;cancellables)<br>}</pre><p>Here, we use Combine’s Just publisher to simulate the response and delay to introduce a 1.8-second delay.</p><h3>7. Measuring Performance in Real-Time</h3><p>With the project now running, we can measure the performance of each approach using logs and <strong>Instruments</strong>.</p><h4>Logging Performance</h4><p>We add a simple log function to monitor CPU usage in real-time:</p><pre>func logPerformance(method: String) {<br>    let usage = ProcessInfo.processInfo.systemUptime<br>    print(&quot;\(method) - CPU usage: \(usage)&quot;)<br>}</pre><p>Add this log to the end of each fetch method:</p><pre>self?.logPerformance(method: &quot;Traditional&quot;)<br>self?.logPerformance(method: &quot;RxSwift&quot;)<br>self?.logPerformance(method: &quot;Combine&quot;)</pre><h4>Using Instruments</h4><ol><li>Open <strong>Instruments</strong> in Xcode (Command + I while the app is running).</li><li>Select <strong>Time Profiler</strong> to measure CPU usage, memory consumption, and execution time.</li><li>Hit <strong>Fetch Data</strong> in the simulator and observe the differences between the three approaches.</li></ol><h4>Performance Comparison Table</h4><p>Now that we’ve implemented the three approaches, let’s summarize the performance differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*p6hUa_y5I-6kP6fp6ylNnQ.png" /></figure><h3>When Not to Use Reactive Programming</h3><p>Although reactive programming offers numerous advantages, it’s not always the best choice. Here are some scenarios where it might not be viable:</p><ol><li><strong>Simple Applications</strong>: For apps with few screens and limited interactions, adding a layer of reactive programming can be overkill. The cost of learning and the added complexity may not justify its use.</li><li><strong>Learning Curve</strong>: For teams new to reactive programming, the time needed to learn concepts like observables, publishers, and operators can delay development, especially if the benefits aren’t clear for the project’s needs.</li><li><strong>Synchronous, Simple Operations</strong>: If your app mainly deals with synchronous operations, such as button taps or simple navigation flows, the additional complexity of reactive programming may not bring significant benefits.</li></ol><h3>Which Approach Should You Choose?</h3><p>Choosing between <strong>RxSwift</strong> and <strong>Combine</strong> depends on your project’s needs and platform requirements. <strong>Combine</strong> is the best choice for new projects that target the Apple ecosystem and benefit from its native integration. <strong>RxSwift</strong> remains a solid option for legacy projects or those that require multiplatform support.</p><p>Here’s a quick recap:</p><ul><li><strong>Combine</strong>: Best for new, SwiftUI-focused projects targeting Apple platforms.</li><li><strong>RxSwift</strong>: Ideal for legacy or multiplatform projects with existing Rx implementations.</li><li><strong>Traditional (Non-Reactive)</strong>: Suitable for small, simple apps with minimal complexity.</li></ul><p>The real-time comparison in this project showed how each approach performs in terms of execution time and resource consumption. Testing these methods on your own projects will give you a better sense of which one fits your needs the best.</p><blockquote>Now that you understand reactive programming, try implementing it in your current or next project and see the difference it makes!</blockquote><blockquote>Happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3261e15f3a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile Development and Security: A Revolution in 2023]]></title>
            <link>https://medium.com/@herlandro/mobile-development-and-security-a-revolution-in-2023-7108b85ab79d?source=rss-90897b12daf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7108b85ab79d</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Herlandro Hermogenes]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 20:40:11 GMT</pubDate>
            <atom:updated>2024-10-30T20:57:05.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vf0QBQ8qDk2a1wCHx2Pwpg.jpeg" /></figure><h4>Artificial Intelligence, 5G, Blockchain, and the Trends Transforming App Development</h4><p>One of the fastest-moving industries, mobile development faced serious changes in 2023, especially in terms of security and integration of emergent technologies such as AI and 5G. That is why the growing demands for personalization, speed, and safety open completely another world of challenges and opportunities for developers. That’s why we have prepared for you a brief overview of the most important app development trends and some best security practices that keep user data safe.</p><h4>1. How does the integration of AI and Machine Learning revolutionize mobile app development?</h4><p>Wow, what an interesting question! AI and machine learning are changing this course of mobile app development in which applications can now predict users’ needs with greater accuracy. Think about how it will be to receive app experiences curated according to predictive analytics, making them more usable and appealing to their users. With increased growth in AI, there comes increased ability developed in apps to create sophisticated-interaction-type experiences. AI and ML make the mobile apps virtually psychic sidekicks. Just think about it: your app knows what you want before you know it. It’s that friend who always knows where you want to eat before you’ve even decided. But instead of pizza, it’s seamless experiences, personalized on a platter. What if the app trolls me and makes me eat more salad?</p><h4>2. What are the main design trends of mobile apps in 2024?</h4><p>Oh, this one’s going to be a blast! In 2024, the design landscape for mobile applications mostly faces minimalistic aesthetics coupled with neomorphism. This concept would round up on minimalistic-looking interfaces that are subtly inlaid with three-dimensional elements for depth and visual interest. The emphasis is on user-friendly design that balances both form and function. It’s one of those designs where you just need to swipe further just to see what’s next.</p><h4>3. How does 5G influence mobile application development?</h4><p>Great question! 5G gives your app a turbo. This 5G technology is going to be a game changer for mobile application development because the data speed is very immense, and the latency is very less. It streams in instantly, it makes real-time applications even more responsive, and allows deeper immersion in AR. And as 5G becomes ubiquitous, it will power a whole new generation of high-performance mobile apps. Remember how long it took for those videos to buffer? Yeah, that’s over.</p><h4>4. What is privacy-centered development, and why is it of great importance today?</h4><p>Privacy-now that’s a buzzword if there ever was one. Seriously, though, considering all the recent data breaches and scandals, privacy-centered development is like having your users’ data with a security guard in front. Privacy-centered development is a framework oriented toward the security of user data by preventing unauthorized access to and breach of such sensitive information. In an era defined by increasing vulnerability regarding data, only substantial measures regarding privacy can be followed. This would encompass strong security with the maintenance of transparency for gaining and retaining user trust, as well as adherence to regulation. It is not just a question of locking the front door but digging a moat, raising the drawbridge, and stationing a few dragons for good measure. Because who doesn’t get tired of hearing about the next big leak of data?</p><h4>5. What does best practice look like for data security in mobile apps?</h4><p>Data security is like that extra layer of bubble wrap we all love-essential yet often underrated until an issue arises. Strong encryption in place, session management that’s secure, and multi-factor authentication need to be considered for securing data in mobile applications. These practices would cover most of the bases of protection against many types of potential threats and protect user information against unauthorized access and data breaches. Wrap your data in protection such that even the most determined hacker would give up.</p><h4>6. How can developers defend against session attacks?</h4><p>Session attacks-pretty much like someone crashing your house party without an invite. Protection against session attacks involves a number of strategies that include the use of HTTPS, secure session identifiers, and the short-term expiration of sessions. Thus, by allowing the developer to minimize the chances of unauthorized access when it manages and terminates sessions in case of inactivity, the integrity of user interactions is kept intact. It is all about keeping your data as secure as your best friend’s birthday party guest list. Do you want crashers at your parties? Yeah, let’s keep the bad guys out!</p><h4>7. What role does blockchain take up in mobile app security?</h4><p>Blockchain is like the bouncer of the club, never letting anyone in behind other people’s backs without showing IDs. It is all about secure authentication, making transactions as unchangeable as a date on your passport. Blockchain technology secures your mobile application by introducing an entirely new decentralized approach in the validation of transactions and integrity of data. Immutability and transparency properties make it a perfect tool against fraud and for secure authentication in a mobile app. Like adding that added layer of the ‘nuh-uh, you’re not getting in here’, making life hard for those hackers. Who here is all about making life hard for hackers?</p><h4>8. Why is it so hard to make safe IoT devices?</h4><p>IoT security-now that’s like trying to keep all the cats in a room docile. So many devices of different types, with no universal standards in place-the jungle out there is literal. Securing IoT devices becomes difficult due to the different natures of various devices and a lack of standardized security protocols. Ensuring secure encryption and periodic updates would be crucial in mitigating these risks. The use of such practices by the developer ensures greater protection of IoT networks against various vulnerabilities.</p><h4>9. What is your vision regarding the prospects of mobile development within the next five years?</h4><p>What’s the future of mobile development? Well, instead of seeing a crystal ball with vague predictions, during the next five years I envision mobile development blowing the roof off with AI integration, 5G, and edge computing. They are going to be used in quicker and more intelligent app development and also context-sensitive ones, which will keep on improving the user experience and application capabilities. Who’s hyped about their applications reading their minds?</p><h4>10. Why is accessibility important in mobile application development?</h4><p>Accessibility — now here’s where we make sure everyone gets to join the party. It is not just being inclusive, but making our apps usable by everyone: from grandmas to gamers. Accessibility in mobile application development ensures that applications are usable by individuals with diverse abilities and needs. Other than that, developing with accessibility in mind will bring inclusivity, a broader user base-not just meeting the bare minimum in terms of legality. The more, the merrier, trust me, because when your app works for everyone, everybody wins!</p><p>Drop your comments below and let’s get the conversation rolling!</p><p><strong><em>If you’ve enjoyed this interview, </em></strong><a href="https://medium.com/@herlandro/subscribe"><strong><em>subscribe</em></strong></a><strong><em> and get an email as soon as I publish!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7108b85ab79d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>