<?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 Can Akyıldız on Medium]]></title>
        <description><![CDATA[Stories by Can Akyıldız on Medium]]></description>
        <link>https://medium.com/@canakyildz?source=rss-25884b2645e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rfFthrsEXdq3DbuK</url>
            <title>Stories by Can Akyıldız on Medium</title>
            <link>https://medium.com/@canakyildz?source=rss-25884b2645e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:22:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@canakyildz/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[Mixing C++ And Swift: From Obj-C Bridging Layers to Interoperability]]></title>
            <link>https://medium.com/@canakyildz/c-and-swift-mix-from-obj-c-bridging-layers-to-interoperability-c558238c5b52?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c558238c5b52</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 17:03:06 GMT</pubDate>
            <atom:updated>2023-12-22T17:03:46.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdnsTnD1Q-gjZJXoPzw-tA.jpeg" /></figure><h3>Introduction</h3><p>Today, I would like to talk about this new feature of how Swift and C++ can work together without Obj-C bridging layers in Xcode 15 through interoperability.</p><p>Initially, Swift was designed to be interoperable with Objective-C, which is a C-based language. This was crucial because many existing iOS and macOS applications were written in Objective-C, and integration was allowed for gradual adoption of Swift.</p><p>Before Swift and C++ interoperability, integrating C++ code into Swift projects required a bridging layer. This typically involved using Objective-C as an intermediary, which added complexity to the development process. Additionally, imagine how complex and time consuming process you would need to go through when creating these bridges. But now, we don’t need a bridging layer.</p><p>First, I’ll cover the basics of how you would interact with C++ through Bridging layers. After that, I’ll demonstrate how to make C++ functions work smoothly and safely in Swift without bridging layers through interoperability.</p><h3><strong>Get started: Creating our project and framework</strong></h3><p>First we are creating our project, we are choosing the Storyboard interface and then we can choose language of Objective-C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4G5iH84t6ImLtRSTm7XArg.png" /></figure><p>Afterwards, we are creating our framework in the project, language should be Objective-C and you should choose project of MathDev, then embed it in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF5L7L6gGk29HgmDCE3yNQ.png" /></figure><p>And we will have this folder structure after creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MVAl4H9vc_VVzd9tOWnszQ.png" /></figure><h3><strong>Bridging Layer and View Creation</strong></h3><p>Before we create our C++ files and functionalities, let’s navigate inside MathDev folder and create MathOperationsView which is SwiftUI view. Then you will be presented with this pop up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLixuL8siDaINQZkm9C9cQ.png" /></figure><p>Click on Create Bridging Header, then you will be given .h and .mm files. Move them to our <strong>MathOppps</strong> <strong>framework. </strong>Make sure you select the right target though.</p><p>If you want to follow my file names and so on, I have changed my Bridging layer’s file name to <strong>MathOperationsBridge</strong>, so we go to our Target &gt; Build Settings &gt; Search for “<strong>bridging</strong>”</p><p>Then change file name and source path of the layer to the new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_JQNw2JQaIwa7MPx9BVCQ.png" /></figure><p>Now our structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*OhzN8MKT4hKcRH9pnPwudw.png" /></figure><h3><strong>Introducing C++ to Project</strong></h3><p>So as you can guess from the project naming, we are going to be doing some Math operations. Such as adding subtracting and multiplying. I wanted to keep it very simple (not that I’m a C expert) so we all can focus on and understand the concept better including myself.</p><p>Let’s start by creating a C++ file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEM2SlIXSNRp6lOEvwmShA.png" /></figure><p>We will call our file MathOperations, which will have extension of .cpp</p><p>Make sure you also create a header alongside which will have an extension of .hpp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5MA4Pbllm8wmIoOxL7eEw.png" /></figure><h3><strong>C++ Implementations</strong></h3><p>First, we make sure we add lines of #ifdef __cplusplus and #endif to the end. The <strong>MathOperations</strong> class is defined within a C++ context, indicated by <strong>#ifdef __cplusplus</strong>. So eventually this ensures that the class is only compiled in a C++ environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*w1d9Oe1FNC41klgGMRI3vw.png" /></figure><p>Afterwards, we will create our class of MathOperations, make the content static and public. These are basically protocols if you are not familiar with Swift or Obj-C. We define so our Bridging layer or layer on SwiftUI can acknowledge these methods outside the scope.<br>As you could guess, we are going to pass doubles of “a” and “b” to achieve functionalities of adding, subtracting, multiplying and dividing.</p><p>Then we move to our .cpp file and do the basic math there. The double MathOperations::add(double a, double b) is basically how you would create a method in Swift to pass two params of doubles, return a double.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*vD61nsa4CCmF8-WkBxHZzw.png" /></figure><p>Alright! We have our C++ header and source implementation file. So it’s a good time to move to Bridging layer!</p><h3><strong>Implementations of Bridging Layer</strong></h3><p>Before getting to implementations of header and source, basically our .mm file will bridges C++ code (<strong>MathOperations</strong>) with Objective-C, making it usable in Swift.</p><p>To explain<strong> #import “MathOperationsBridge.h”, </strong>it basically Includes the Objective-C interface for the bridge. And <strong>#include “MathOperations.hpp”</strong> includes the C++ class definition that we worked on earlier, so the methods in header are accessible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*KcrggXVFAhMduM27-w8YRg.png" /></figure><p>And as far as Usage of<strong> “::” in C++</strong>: , it is like using “<strong>.”</strong> in Swift, but for static methods in C++. For example, <strong>MathOperations::add(a, b)</strong> calls the <strong>add</strong> method on the <strong>MathOperations</strong> C++ class.</p><p>Now moving on with our bride layer header, we navigate to the file of MathOperationsBridge.h</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*v5MyQRhTNn2Dz4VnPrY8aw.png" /></figure><p>To first give a quick explanation to methods that start with a <strong>+</strong> sign. In the world of Objective-C, they are class methods and class methods are like those helpful tools you can use without needing to own the tool — you just borrow it whenever you need it.</p><p>The <strong>NS_ASSUME_NONNULL_BEGIN</strong> and <strong>NS_ASSUME_NONNULL_END</strong> macros are there to tell other developers (and the compiler) that, unless explicitly mentioned, all pointers in this interface are assumed to be non-null. It’s a way of saying, “I expect all inputs to be actual values, not ‘null’ or ‘nothing’.”</p><p>So this was everything we needed as far as Bridging of Obj-C and C++ code. Next we need to update our MathOppps.h file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WigcBOfX3Ai1IKpUXp7aXg.png" /></figure><p>Besides the stuff that was auto created, we add lines of <strong>#import &lt;MathOppps/MathOperationsBridge.h&gt; </strong>and<strong> #include &lt;MathOppps/MathOperations.hpp&gt;</strong>. For primary reason of letting the MathDev access the content in MathOppps that we want to use in our view.</p><h3><strong>Usage of Bridge Layer in SwiftUI View</strong></h3><p>We navigate to MathOperationsView.swift file, import MathOppps (make sure you added this module to our project as target).</p><p>Then, since the Bridge layer’s methods are static, you can directly call them like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*HgbiFFAEGnYrbaEPks8dVA.png" /></figure><p>And that’s literally it, this is how it goes.</p><p>Now we want to move forward with the new technology we are given. Interoperability of C++ and Swift without Bridging layer.</p><h3><strong>How to use the new feature of Interoperability of C++ and Swift without Bridging Layer</strong></h3><p>First, go to Targets &gt; Build Settings and search for “interoperability”. You will see Swift Compiler — Language, and we want to change this from C/Objective-C to C++/Objective-C++ FOR both of the targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FuQYM35Ox78cYKhL28egIw.png" /></figure><p>Afterwards, we want to tell Xcode we are not using any bridging layers. Again by going to Target &gt; Build Settings &gt; Searching for “bridging”. When you see it, just remove the content that we had initially modified to match our newer naming for layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFwg9Yy-L1K23ujbQAoxcA.png" /></figure><p>Next, you can either remove bridging files we created or leave them as it is. Totally up to you. But very first thing to do is update the file of MathOppps.h like this below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGSh8H01V4nEC1R0cDe9ow.png" /></figure><p>So we are saying our compiler that you no longer need to know about no bridging layer.</p><p>Now if you go to the view file and update the code like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myzSXwgctsHQdK5rOksQ9g.png" /></figure><p>And as you could see it’s working perfectly fine.</p><h3><strong>Conclusion</strong></h3><p>So that was pretty much it. If you have a large amount of C++ containing codebase, you can gradually update your code by getting rid of Bridging layers. Obviously keep in mind that this feature is XCode 15+ and iOS 17+ supported!</p><p>Thanks for reading and wishing you a nice weekend everyone!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR7cGTu1YQqWZdsp6OqPUg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c558238c5b52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detailed @Observable through Swift Macros]]></title>
            <link>https://medium.com/@canakyildz/hello-everyone-fecf943e0175?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fecf943e0175</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[observation]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Sat, 16 Dec 2023 19:14:11 GMT</pubDate>
            <atom:updated>2023-12-21T08:07:36.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqmvL0xrupOs24-cZ8RVSg.jpeg" /></figure><p>Hello everyone!</p><p>Today I will be talking about Observation feature in SwiftUI that lets you define your models using <strong>@Observable</strong> which is built with new Swift Macros feature to have a reactive behavior for your swiftUI views to respond to changes in that model.</p><h3><strong>Introduction</strong></h3><p>Observation feature has very similar dynamics as ObservableObject. But instead of all the property wrappers and protocols, we are assigning macros and then never deal with @Published or some Object property wrapper.</p><p>Since <strong>@Observable</strong> is a macro, initially we will be looking at implementations behind declarations that wrap things up for us and clearing our models from writing @Published or Object wrappers in our views. Then we will be showing what&#39;s changed, comparing the whole thing with ObservableObject components and how we can use this new feature.</p><p>So let’s tap on <strong>@Observable</strong> and see what’s up!</p><h3>Under the hood of things (A bit more advanced)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fnUQG-CKH4ULu5mDd63Gw.png" /></figure><p>We have a few macros under the tree of @Observable macro. I will try to explain things on a high level as much as possible. Let me clear a better picture with some visuals.</p><h4>Expanded state of @Observable Macro</h4><p>So we will have this example struct called <strong>CarGallery</strong>. To cover macro side of things first, our end product would look like this on the left, then when you expand it, we would see the expansion on right side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ywys1srU5rNVseustP6KMQ.png" /></figure><p>We could see a lot of thigns going on when macro is expanded, like ObservationTracked macros, ObservationIgnored registrar let decleration, non isolated functions, extension to Observable.. a lot of things!</p><p>Lets go by moving from the root and to surface level.</p><h4>@attached(extension, conformances: Observable)</h4><p>This conformance/extension macro is helpful with making our class conform to <strong>Observable</strong> protocol. Which is a type that emits changes upon receiving notifications. But important to note this quote from Apple docs:</p><blockquote>Conforming to this protocol signals to other APIs that the type supports observation. However, applying the Observable protocol by itself to a type doesn’t add observation functionality to the type. Instead, always use the <a href="https://developer.apple.com/documentation/observation/observable()">Observable()</a> macro when adding observation support to a type.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRWaOVjp4tfk9FtQGjIApQ.png" /></figure><p>If you are finding this new concept hard to understand after your learning days, I would highly recommend that you can consider it similar to ObservableObject conformance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edH0EGISo6JQUpFxKXMVhA.png" /></figure><h4>@attached(memberAttribute)</h4><p>As far as memberAttribute, it helps with adding <strong>@ObservationTracked</strong> keyword/attribute when <strong>@Observable</strong> macro is expanded. <strong>Just attribute adding</strong>.<strong> It doesn’t create the functionality behind ObservationTracked</strong>, that would be done by <strong>Peer Macro </strong>which we will go over in a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQwNIqCZrZCbfLK73Lmq3g.png" /></figure><p>I would compare this to @Published attribute, they are most probably working under the same dynamics in my opinion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ik-hf6ovkbDcncT5rwlhmg.png" /></figure><h4>@attached(member)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBijIAg5xmJ0Cy8PUBN03Q.png" /></figure><p>what <strong>@attached(member) </strong>does is that it creates members of<strong> _$observationRegistrar</strong> which is initializing<strong> ObservationRegistrar </strong>class<strong>,</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEb6N-LuD70sPOd9vPbg9g.png" /></figure><p>which contains all of these methods above that we will be using down below.</p><p>Afterwards, it creates method of <strong>withMutation</strong> and <strong>access</strong> as you can see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WDB2qqVRAiEQQGY_z1iDng.png" /></figure><p>Those are mainly helpful with observation and tracking changes by using <strong>ObservationRegistrar</strong> methods. When you make a change, under the hood they are updating our properties, working in coordination with <strong>Peer</strong> macro of <strong>ObservationTracked</strong>.</p><h4>@attached(peer)</h4><p>This is the whole functionality behind <strong>ObservationTracked</strong> attribute you see. Actually it’s <strong>ObservationTracked</strong> attribute itself but we are not able to apply this macro without<strong> Member Attribute</strong> macro’s help, which is because it will be the one who puts this macro on map by a little renaming.</p><p>So originally it’s built under the class of <strong>ObservationTrackedMacro</strong> struct, of type <strong>PeerMacro</strong>. I can only imagine the craziness and amount of code in its creation — because hell mate! <strong>PeerMacro</strong> is a badass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tN-obN5d4u2CBS6x1Pz2yw.png" /></figure><p>If you are any more curios in macros, you could check my Swift Macros article/video to learn more about them.</p><h3><strong>@Observable In Practice</strong></h3><p>A good example would be showing how things are replaced. When we were dealing with <strong>ObservableObject</strong>, we were adding the protocol conformance, @<strong>Published</strong> property wrapper for each and every variable that we want to listen changes of and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVBLDp2DZOCHvVnXLGXbDg.png" /></figure><p>Now picture has changed to be like this above.</p><p>When using this <strong>CarGallery</strong> in our SwiftUI View, we have made a transition of no longer needing to use <strong>@ObservedObject, @StateObject</strong> but directly define with a let declaration like here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8NDz9eVC6bvSDYzfx-LrQ.png" /></figure><p>It will automatically update our properties in the <strong>CarGallery</strong> model.</p><h4>Array of Observables</h4><p>Let’s also see how we can work with an array of <strong>@Observable</strong> marked objets and comparing with older version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RQlaku-2B9RzR7xSVSTqQ.png" /></figure><p>I would call this probably my favorite feature of the whole feature, because I literally hated creating another <strong>observable object</strong> to contain the list of items.</p><h4>Binding</h4><p>And looking at how <strong>@Binding</strong> was affected, we don’t see a lot of apparent changes, but here it is!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVhOxU4qEr6uGX2uosuSJA.png" /></figure><p>We can just add a <strong>@Bindable</strong> property wrapper and we will be fine!</p><h3>Conclusion</h3><p>That was pretty much it guys! I hope it was helpful to you and I’m wishing you a nice day! Happy coding</p><p>Goodbye.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvB3UJBDdeU--an8TzrPlQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fecf943e0175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Macros: Detailed & Practical Understanding]]></title>
            <link>https://medium.com/@canakyildz/swift-macros-detailed-practical-understanding-829d88d337fb?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/829d88d337fb</guid>
            <category><![CDATA[wwdc]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift-macros]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 15:31:10 GMT</pubDate>
            <atom:updated>2024-03-05T16:15:46.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eQWECEAhhPCsYGktTOzTg.jpeg" /></figure><p>Hey guys, today I will be talking about Swift Macros.</p><p>Macros before June 2023, were built-in and not modifiable or buildable.<br>They were source level components that if you were to create a macro, you had to go through a certain scenario with apple where you need to make proposals, prove why it’s needed and what it does and then get approved by them to get it added.</p><p>Now, after introduction of macros in June 2023 as a beta software and by September it’s available for everyone to use at home. You can declare a macro without any approval from anyone.</p><h3>What are Swift Macros?</h3><p>Swift macros are like smart shortcuts that add extra code for you when you’re building your app. Everything happens at compile time so This helps make coding easier by being less repetitive, and less error prone.</p><p>There are a two primary types of macros that are <strong>Freestanding</strong> and <strong>Attached Macros</strong>.</p><p>I would like to begin with introductions of these macros, then I will dive deep in their inner types and give building examples.</p><h4>Freestanding Macros</h4><p>We are not very unfamiliar with freestanding macros as we have seen them and used them before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*-5hawKsfdBvUnKZ28lyULw.png" /></figure><p>Like in this example, the method is using #warning and #function macros.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdEiiFM3rgIZSzXNjCgeyQ.png" /></figure><p>They are created like this above and we will learn more about its creation in a bit</p><p>You might think of <strong>@inlinable </strong>as somewhat similar. <strong>@inlinable</strong> lets the Swift compiler decide if a function’s code should be inserted directly at each place it’s used (this is called inlining) for efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbpiNU8PvNrFAapD2QpuMg.png" /></figure><p>But with Freestanding Expression Macros, this inlining happens every time, automatically.</p><h4>Attached Macros</h4><p>They only modify the declaration they are attached to. Those are the ones that start with the ‘at sign @’ before declaration.</p><p>Like SwiftData’s @Model macro or @Observable from reactive programming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*9ygD1Io4VydlTscBeyMVYw.png" /></figure><h3>Get Started: Setting up things</h3><p>Firstly, open Xcode and go to File &gt; New &gt; Package</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHLyXRJetTzKMkDuDfstsw.png" /></figure><p>This package will be available for us to use in our projects, but initially we can create them separately.</p><p>Select SwiftMacro template from multi platform section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoLdqKLdwgq82HAlDa9Wgg.png" /></figure><p>Then we will be presented with this default set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gO5UW65nAIgU9WEbCzclNg.png" /></figure><p>Please note that we will be using these folders so I might say “hey let’s go back to main file”.</p><h3>Understanding Different Cases of Macros</h3><h4>Expression Macros (Freestanding)</h4><p>Expression macros are used for generating values or performing actions at compile time.</p><p>We have an example which is going to help us get the square of number we pass in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVQPp-CeAfeBD3_DekHJZQ.png" /></figure><p>Let’s see how it’s actually being created.</p><p>First, just like in our default set up from Xcode when we first created our Swift Macro, we will need to create a macro like this in MyMacroMacro file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgO4e0ecG5PWq--mc1LrRQ.png" /></figure><p>After we define our Macro, we get an error that yells us with the needed set up we need to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEWPBo9XHyDSroQjYa_Q5w.png" /></figure><p>As we conform to protocol and get needed method there. The expansion so-called method is going to be seen in all of the macro creations, it basically represents expanded state of a macro. You also see <strong>node</strong> and a return of <strong>SwiftSyntax.ExprSyntax</strong>.</p><p><strong>What is node?<br></strong>Node will be helpful with retrieving the passed information or lets say the information that is passed to macro. Which will contain arguments, descriptions, types and so on. It will be more clear in a moment when we do the implementation of ComputeSquareMacro.</p><p><strong>Why are we returning SwiftSyntax.ExprSyntax?<br></strong>Well what we are doing is basically writing low level code to create syntax, there are lower levels obviously but this environment or framework that we see is basically a wrap up of lower logic so we can understand.</p><p>To continue with our <strong>ComputeSquare</strong> ExpressionMacro, we can do the implementation like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5kX80Om69TJTVNdwJE6xQ.png" /></figure><p>Again, node is allowing us to access arguments passed to macro, and first argument from argumentList is the number that we passed earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDGPTP0a0OhPbqmG2oH7NQ.png" /></figure><ul><li><strong>argumentList</strong> first is number parameter in the method, imagine we had other parameters in there. So to specify or access a specific parameter, we work with <strong>argumentLists</strong>.</li><li><strong>literalValue</strong> is how we obtain this in the boundaries of integer syntax by telling compiler this argument is a type of <strong>IntegerLiteralExprSyntax</strong> and we obtain the <strong>literal</strong> <strong>text</strong>, then we wrap it in a <strong>Int</strong> type.</li></ul><p>Now let’s get back to <strong>main</strong> file and then select the right target as seen on the screenshot also make sure you select <strong>Mac</strong> for testing purposes, you can see the desired effect being display on the debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zM3-y2dLPzX7yV9ANO3qyg.png" /></figure><h4>Declaration Macros (Freestanding)</h4><p>Declaration macros basically automate the creation of data structures or other declarations.</p><p>In our example we want to create an struct from arguments. Let’s say this structure has a value and we want to access it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*3EQxWilON6gjC6ppEC2Vcg.png" /><figcaption>We want this to be our result when Macro is expanded.</figcaption></figure><p>Make sure to update your CompilerPlugin, you can either add this new one to the array or remove previous example like I did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*ZC65_nYEmh-esDTFeVJE_w.png" /></figure><p>And here is macro declaration as a freestanding declaration macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3_kWK6A_5uLxBtl2VlVXg.png" /></figure><p>The “<strong><em>names</em></strong>” parameter you see here is basically what names the compiler needs to pay attention to. You need to pass <strong>names</strong> and make sure you match with something because this is not a runtime operation and we need to have things pre defined before we get the code working.</p><p>Now, looking at the implementation of DecloMacroExample struct, we could see that the returned syntax is literally how you would create a structure. Only difference you could see is the argument that is being passed which is what we pass as value from our client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zg-h6DZ40pV6S-LlN1tHTA.png" /></figure><p>An important note that you need to make sure struct’s name must match with macro like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlpTG3_ZWudScLV2mgOCYA.png" /></figure><p>Now if you go back to the main file and add the line of <strong>#createStructWithValue(“”)</strong> and pass a value in the parameter, and also add a assert testing <strong>assert(DecloMacroStruct.value == “Cancodeswift”)</strong>. And it should work fine.</p><p>To see the details of the macro you can tap on the macro and click on expand</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*m9lKNkbhGY9NaucPqRri2Q.gif" /></figure><p>And you will see that the source is there.</p><h3>Attached Macro Types</h3><p>Now we can continue with Attached macros. Attached macros have more types compared to freestanding ones. And I would say some of them are more complicated as you need to dig into types more to achieve desired results for macros like Peer Macro.</p><h4>Member Macro</h4><p>Member macros simply add new declarations inside the type they are applied to.</p><p>In our example we want to have a computedProperty member in an enum that will give us websites of cases.</p><p>We want to achieve this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*YNKiyOTa0y2UgoGgNp_wNQ.png" /></figure><p>And when @WebsiteGiver member macro is expanded we will see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*LQ0-KzZtEskK0c0Vs1OdFw.png" /></figure><p>So basically we want each case to have <strong>www</strong> at beginning; <strong>com</strong> at the end and we also don’t want to write website variable.</p><p>So first, lets start creating our macro starting from <strong>MyMacro</strong> file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqTJQUHe93tslgExcxC5Uw.png" /></figure><p>If you noticed, it’s not freestanding marked anymore, and we also have something called <strong>arbitrary</strong> that is passed to names, this will make things more generic for us.</p><p>And lets see how <strong>EnumMemberMacro</strong> is created</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*ZoPvwVo2Kb3yk_NmKPt8cA.png" /></figure><p>First we created our struct and conformed to <strong>MemberMacro</strong> protocol and we will be presented with expansion method that we will need.</p><p>Since we have done this part before and you pretty much guess what’s going on with conformance, let’s continue directly with implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*nPLNlNK6-FNSWvFXnlyP_w.png" /></figure><p>We have <strong>membersBlock</strong> accessed from declaration, which will allow us to work with all cases. We are first <strong>compactMap’</strong>ping each item to be type of <strong>EnumCaseDeclSyntax</strong>, this will help compiler understand that we are actually working on Enum cases.</p><p>Afterwards, we are mapping members into being ready to use and create our computed property. <br>Rest of it is not really complicated, just syntax that we are familiar with.</p><p>Then you can go back to the <strong>main</strong> file and be able to access website property that we created as a macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*gDpCTcp-kSK16w0OyxWj9A.png" /></figure><h4>Accessor Macro</h4><p>Accessor macros are usually applied when working with properties, to turn them into computed properties.</p><p>As you can see in the example, on the left we have a struct that contains a dictionary and a computed property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hbp508urjYFM0LRaRnaXQ.png" /></figure><p>What accessor macro can help us with is, take us from implementation on the left side to right side.</p><p>Again, we go to our <strong>MyMacro</strong> file and create this. The dict that you see in <strong>names</strong> param is basically to tell compiler to know what our dictionary will be called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ru6jSBPGToxx287Rz86vsw.png" /></figure><p><strong>Why it can’t be generic with arbitrary?</strong> is a possible and good question that I can only answer with- it has to be compiler waking like freestanding macros, I could not find enough sources to go deeper but more macros are needed for me to use more I will dig deep and make more articles and videos.</p><p>If we continue with the <strong>StoryingGuyMacro</strong> struct implementation, this time we are not going through <strong>argumentList</strong> or <strong>arguments</strong> but <strong>bindings</strong> and <strong>declaration</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7jfArqSd9V8kalTrSEyBQ.png" /></figure><p>We declared “<strong>varDecl</strong>” from declaration value and casted it as <strong>VariableDeclSyntax</strong>, which then is going to let us access bindings, obtain first one and then get the variable’s naming and look for it in our <strong>dictionary</strong> or set its dictionary field to the new value.</p><p>As our next attached macro, we are continuing with <strong>Member Attribute </strong>but we will actually be adding on to <strong>Accessor Macro</strong> and combine them together.</p><h4>Member Attribute Macro</h4><p>Member attribute macro is a macro that helps with adding an attributes to your types or extensions. If we look at our previous example , we had this happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NwFXtDwA707bybDRN6-_w.png" /></figure><p>But imagine now we have another property other than surnameProp or even many more.</p><p>So instead of adding this attribute for each property we will have this <strong>MemberAttribute</strong> macro of <strong>@StoringGuyAttributes </strong>and it will help getting rid of the repetitive accessor macro of storing guy but putting it in side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1RrFQpxyOPuu8Th-86_eg.png" /></figure><p>Then when this <strong>StoringGuyAttributes</strong> macro expands it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8GsJ6qC7uMXV4W-F5xUvg.png" /></figure><p><strong>StoringGuyAttributes</strong> member attribute macro will generate properties and <strong>Accessor</strong> macro of @<strong>StoringGuy</strong>. Then we will be able to expand those <strong>StoringGuy</strong> macro that creates computed property work we created before.</p><p>So let’s look at how we are actuating building it.</p><p>First, go to <strong>MyMacro</strong> file and add the line of <strong>StoringGuyAttributes</strong>, type should be same as <strong>StoringGuy</strong> accessor because we will be working with same struct by extending it to create <strong>MemberAttribute</strong> macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVqAgBXNNPOAYWIsRaO_3A.png" /></figure><p>Then, without any modification to Accessor Marco work we did before, just extend the StoringGuyMacro strut and conform to MemberAttribute protocol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwBsq4qSqvaV_Bu5bhZWFQ.png" /></figure><p>Then our implementation will look like this. What’s happening here is that we first create a <strong>guard declaration</strong> that says “<strong>hey, make sure the property that we will apply this attribute to is a ‘var’ declaration.</strong> ” And then by also checking <strong>description</strong> doesn’t contain “<strong><em>dict</em></strong>” regex, we make sure the dictionary we created in the struct is not applying this <strong>StoringGuy</strong> attribute.</p><p>So you can also see on <strong>return</strong> part, we are returning <strong>AttributeSyntax</strong> with the name of identifier called “<strong>StoringGuy</strong>”. <strong>StoringGuy</strong> is again the <strong>Accessor Macro</strong> we created to turn normal variables to computed properties.</p><p>So we are essentially saying “hey apply <strong>StoringGuy</strong> <strong>Accessor Macro</strong> to variables wherever we apply this <strong>MemberAttribute Macro</strong> to.” Also as far as <strong>.with modifier</strong>, it’s just making sure we are on next line after we add @<strong>StoringGuy</strong> accessory.</p><p>That’s pretty much it from Member Attribute macro guys. Next we will continue with Peer macro</p><h4>Peer Macro</h4><p>Peer macros are more complicated compared to others, there are not a lot of simple examples to give out and honestly this is another day’s talk to do. So on GitHub I came across a person called <strong>Doug Gregor</strong>, credits to his due, I will go over his example.</p><p>To achieve this result you see of withCheckedThrowingContinuation or withCheckedContinuation depending on marked method’s returning result or not</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*4LrmPz2mfR5QeOKSQziNng.png" /></figure><p>We would create the macro like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-GUJUh2BzNCZ-wWLg7pKQ.png" /></figure><p>And implementation of that would be looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RYdrL6-ahOkv2gdPM4_jlA.gif" /></figure><p>The complexity comes from concurrency and async methods being over crowded on low levels. You can’t just declare the syntax in a string and pass things out. It’s a lot of types and so on.</p><p>But I promise I will do a real scenario implementation on this one in another video and article.</p><h3>Conclusion</h3><p>That was pretty much it from Swift Macros guys, I will be making a separate article and video for Peer Macros later on. I hope you found it understandable and useful.</p><p>Thanks for reading.</p><p>Goodbye.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRPZSOHsOEgmt_Z5aY0GuA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829d88d337fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftData Basics: Replace CoreData]]></title>
            <link>https://medium.com/@canakyildz/swiftdata-basics-replace-coredata-c86300b75337?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c86300b75337</guid>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 17:10:31 GMT</pubDate>
            <atom:updated>2023-12-11T13:14:45.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhL1hL1EbzrblxUhJH97_Q.jpeg" /></figure><h3>Introduction</h3><p>Hey guys, in this article I’d like to talk about SwiftData API that was introduced in the June 2023’s WWDC as a beta software. It’s important to mention that SwiftData is an iOS 17 API and works compatible with XCode 15.</p><p>SwiftData is basically there to replace CoreData to make it easy to persist data using declarative code. It’s designed to integrate easily with SwiftUI.</p><p>Compared to CoreData, it’s easier and more clean to deal with persistent data. You don’t need to create another Xcode file and handle data management from there.</p><p>I’d like to show you a couple things with its root source so let’s start by checking the details of this API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxsAhS_0VbxXLLuemKI6pg.png" /></figure><p>We could see FetchDescriptor that we had when we were dealing with CoreData. Also here you could see we have more stuff that’s coming from CoreData like hasChanges(), rollback() , save() and so on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4g06cshv_ISVMIYn0Lh5XQ.png" /></figure><p>Well this is simply because SwiftData is built on top of CoreData or let’s say it’s a combination of CoreData’s persistence technology with Swift’s modern concurrency features. As mentioned on Apple’s documentation.</p><p>Now let’s get going with how we work with it.</p><h3>How to get started</h3><p>If you create a new project on Xcode 15, you will see on storage section SwiftData as an addition to CoreData</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLy24Kx9mXHJcglD_PKHiw.png" /></figure><p>If you choose it and create the project, you will have a default set up.<br>So to keep it short and simple, I want to go over this default thing we see here.</p><p>First let’s look at the ProjectApp file that creates our source of application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FViN3N4mnhfnwKq2PhlVtA.png" /></figure><p>You could see that we have a ModelContainer, this is where the data is saved, it’s pretty much same as how it was on CoreData but we have an easier way to do it if we don’t need any configuration. <br>Which is if you remove the sharedModelContainer property, you can update your .modelContainer modifier like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQ8sngxoRlW_S3ouqIwIKA.png" /></figure><p>And this modelContainer modifier will allow you specify what data model you want to inject to your views, you can do this for any view that will contain a persistence data. So it’s not only for the root view of your app.</p><p>Let’s continue with the smallest component — Item data model. To create a persistent data, first thing you will need is an object. In this default example it’s “Item”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*aN3xfB6dxvxDmP-iMfmVTA.png" /></figure><p>This is all you need to create a persistent data object and If you noticed; It’s marked with @Model Swift Macro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*FreY_OuOEo61IL7bVFthRg.png" /></figure><p>And if we look at the details of that, it’s looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hga73IZHctqXRVtSz1FEdQ.png" /></figure><h4>What is this Swift Macros?</h4><p>Well since this article is about SwiftData, I won’t be going over in detail what is a macro. But basically Swift macros automatically transform and add new code to your program during compiling time, saving you from writing repetitive code yourself.</p><p>They ensure that both the input and output code are correct and error-free in terms of syntax and data types. This makes your coding more efficient and reduces the chances of bugs or misuse of macros.</p><p>A reference from docs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LllJ8RLcSMV38TeMLJP1BQ.png" /></figure><p>To get back on the default example, lets continue with the view that it has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*ww3KvROO6rPtQA5wcE7sAA.png" /></figure><p>If you are wondering the folded parts, I have folded some parts of code here that is just typical way of handling view creation to focus on SwiftData itself.</p><p>On top, we have a SwiftData importance alongside SwiftUI.</p><p>And you could see we have a modelContext creation with @Environment property wrapper that calls ./modelContext</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*4N1Vo8txnX-eRl2D-ddzZw.png" /></figure><p>Context is something that helps you interact with data itself. Such as to save data, delete data and fetch data we use model context.</p><p>And these methods in the screenshots are basically how you delete and add new data to the your storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUB8r7wLzwAO1t7ifBddqw.png" /></figure><p>As far as Query annotation that’s declaring a list of items, It’s basically how you retrieve your data model. Yes. Literally. That’s easy as it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*D9TKA3ns2H42TRw_JhVqTA.png" /></figure><p>But additionally or for your specific case, you have some options like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*9W56iXw0kEIbTidsUnclyw.png" /></figure><h3>Conclusion</h3><p>As a conclusion, SwiftData is pretty practical and looks like it will replace CoreData usage for developers who especially prefers SwiftUI for creating their views. Again it’s good to keep in mind that there is a version disadvantage which is coming from its being for iOS 17.0 and Xcode 15.</p><p>That was pretty much it guys, thanks for reading!</p><p>See you on the next one!</p><p>Goodbye.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDTwpnMdXGapim4qkzaTZg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c86300b75337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced: SwiftUI State Management]]></title>
            <link>https://medium.com/@canakyildz/advanced-swiftui-state-management-3816d804477e?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3816d804477e</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 16:06:08 GMT</pubDate>
            <atom:updated>2023-12-04T16:06:59.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xZdMwXAG1oErCtSOnus0g.jpeg" /></figure><h3>Introduction</h3><p>Most people who are developing apps using SwiftUI or maybe additionally Combine, have been doing state management and they know how the things work overall, and how it helps in different cases. In this article I’m not aiming to mention the common things, I will be trying to mention how they work underneath and give some advanced examples.</p><h3><strong>@StateObject</strong></h3><p>In SwiftUI, @StateObject is essential for creating and managing observable objects. It’s particularly useful in scenarios where the lifecycle and consistency of the state are critical. An advanced use of @StateObject often involves inner state interactions or the integration of SwiftUI views with complex application logic.</p><p><strong>Underlying Mechanism</strong></p><ul><li>Introduced in SwiftUI 2.0, @StateObject is designed for initializing and owning reference types, particularly ObservableObject instances, within a view.</li><li>The primary difference between @StateObject and @ObservedObject is ownership. With @StateObject, SwiftUI assumes responsibility for the lifecycle of the wrapped object.</li></ul><p><strong>Creation, Lifecycle, and Updates</strong></p><ul><li>When a view containing a @StateObject is created, SwiftUI also creates the object and keeps it alive as long as the view exists. This ensures the object is not destroyed and recreated with each view update, which could lead to lost state and inefficient performance.</li><li>Like @ObservedObject, changes in the @StateObject (through @Published properties) trigger view updates. However, since the view owns the StateObject, SwiftUI ensures that the object’s state is preserved across these updates.</li></ul><p>This makes @StateObject ideal for scenarios where the view needs to maintain a persistent, stateful object that may change over time and trigger UI updates.</p><p>Now let’s continue with an example.</p><pre>import SwiftUI<br>import Combine<br><br>class TimerViewModel: ObservableObject {<br>    @Published var timeElapsed: TimeInterval = 0<br>    private var timer: AnyCancellable?<br><br>    func startTimer() {<br>        timer = Timer.publish(every: 1, on: .main, in: .common)<br>            .autoconnect()<br>            .sink { [weak self] _ in<br>                self?.timeElapsed += 1<br>            }<br>    }<br><br>    func stopTimer() {<br>        timer?.cancel()<br>        timer = nil<br>    }<br>}<br><br>struct TimerView: View {<br>    @StateObject var viewModel = TimerViewModel()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Time Elapsed: \(viewModel.timeElapsed)&quot;)<br>            Button(&quot;Start Timer&quot;, action: viewModel.startTimer)<br>            Button(&quot;Stop Timer&quot;, action: viewModel.stopTimer)<br>        }<br>    }<br>}</pre><p>In this example I wanted to show a <strong>TimerViewModel</strong> using <strong>@StateObject</strong>. The view model manages a timer that updates the <strong>timeElapsed</strong> property every second. The <strong>startTimer</strong> and <strong>stopTimer</strong> methods control the timer’s lifecycle. This demonstrates an advanced use of <strong>@StateObject</strong>, where the observable object is not just a passive data holder but actively manages a process (a timer in this case), showing how SwiftUI can handle dynamic and time-based events efficiently.</p><h3><strong>@ObservedObject</strong></h3><p>@ObservedObject in SwiftUI is designed for scenarios where a view needs to react to changes in an object it doesn’t own. A more advanced use case for @ObservedObject might involve interacting with objects that are being manipulated by multiple sources or participating in complex data flow patterns within an application.</p><p><strong>Underlying Mechanism</strong></p><ul><li>@ObservedObject leverages the Combine framework, which SwiftUI uses for reactive programming. Each @Published property within an ObservableObject is essentially a publisher.</li><li>When a @Published property changes, it emits a new value to its subscribers. In this case, the subscriber is the SwiftUI view that declared the @ObservedObject.</li></ul><p><strong>Change Notification and View Update</strong></p><ul><li>The view listens to these change notifications. When a change occurs, SwiftUI invalidates the view, causing it to recompute its body.</li><li>Similar to @State, SwiftUI uses a diffing algorithm to update only the parts of the view that depend on the changed data, ensuring efficient rendering.</li></ul><p>Let’s continue with an example:</p><pre>import SwiftUI<br>import Combine<br><br>class WeatherDataViewModel: ObservableObject {<br>    @Published var weatherInfo: String = &quot;Loading...&quot;<br>    private var cancellables: Set&lt;AnyCancellable&gt; = []<br><br>    init(weatherService: WeatherService) {<br>        weatherService.weatherPublisher<br>            .receive(on: DispatchQueue.main)<br>            .sink { completion in<br>                switch completion {<br>                case .failure:<br>                    self.weatherInfo = &quot;Failed to load weather data&quot;<br>                default: break<br>                }<br>            } receiveValue: { weather in<br>                self.weatherInfo = &quot;Weather: \(weather.description)&quot;<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>struct WeatherView: View {<br>    @ObservedObject var viewModel: WeatherDataViewModel<br><br>    var body: some View {<br>        Text(viewModel.weatherInfo)<br>    }<br>}</pre><h3><strong>@EnvironmentObject</strong></h3><p>@EnvironmentObject is a powerful SwiftUI property wrapper used to share data across the entire view hierarchy. Unlike @StateObject and @ObservedObject, which are more suitable for passing data between parent and child views, @EnvironmentObject allows views deep in the hierarchy to access shared data without the need for explicit passing. This is particularly useful in large and complex applications where multiple views need to access the same data object.</p><p><strong>Underlying Mechanism</strong></p><ul><li>@EnvironmentObject operates on the principle of dependency injection. It allows data to be injected into the SwiftUI view hierarchy, making it accessible to any view within that hierarchy.</li><li>Internally, when you declare an @EnvironmentObject, SwiftUI looks up the object in the environment of the current view. The environment is essentially a collection of key-value pairs that are passed down the view hierarchy.</li></ul><p><strong>Data Propagation and Access</strong></p><ul><li>When an object is set as an EnvironmentObject at a higher level in the view hierarchy, it becomes available to all child views without the need to pass it explicitly.</li><li>SwiftUI keeps a reference to the environment object and provides it to any view requesting it with the @EnvironmentObject property wrapper.</li><li>When the environment object changes (assuming it’s an ObservableObject), SwiftUI automatically triggers an update in all views that are using this object, similar to @ObservedObject.</li></ul><p>I will be showing you two examples on EnvironmentObject, one of that is very common for handling theme. Well I’m not saying this is the only way to go. You can create an app config object and then pass it across the app with more information. Other one is going to be about authentication which s something you will need to do very close to my execution.</p><p><strong>Example 1</strong></p><pre>import SwiftUI<br><br>class AppSettings: ObservableObject {<br>    @Published var isDarkMode: Bool = false<br>}<br><br>struct ContentView: View {<br>    @StateObject var settings = AppSettings()<br><br>    var body: some View {<br>        NavigationView {<br>            HomeView()<br>                .environmentObject(settings)<br>        }<br>    }<br>}<br><br>struct HomeView: View {<br>    @EnvironmentObject var settings: AppSettings<br><br>    var body: some View {<br>        Toggle(&quot;Dark Mode&quot;, isOn: $settings.isDarkMode)<br>    }<br>}</pre><p>In this example, <strong>AppSettings</strong> is an observable object that holds shared application settings, like <strong>isDarkMode</strong>. <strong>ContentView</strong> initializes <strong>AppSettings</strong> and places it in the environment using <strong>.environmentObject</strong>. <strong>HomeView</strong>, a descendant in the view hierarchy, accesses <strong>AppSettings</strong> using <strong>@EnvironmentObject</strong>. This eliminates the need to pass <strong>settings</strong> explicitly through the view hierarchy, simplifying data flow and reducing boilerplate code.</p><p>Let’s continue with a more advanced app-wide data passing example, something you might need especially authentication.</p><p><strong>Example 2 for App-Wide Data Passing</strong></p><p>Imagine an app that requires a user authentication status to be accessible across all views.</p><pre>class UserSession: ObservableObject {<br>    @Published var isAuthenticated: Bool = false<br>}<br><br>@main<br>struct MyApp: App {<br>    @StateObject var userSession = UserSession()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            RootView()<br>                .environmentObject(userSession)<br>        }<br>    }<br>}<br><br>struct RootView: View {<br>    @EnvironmentObject var userSession: UserSession<br><br>    var body: some View {<br>        if userSession.isAuthenticated {<br>            MainAppView()<br>        } else {<br>            LoginView()<br>        }<br>    }<br>}</pre><p>In this scenario, <strong>UserSession</strong> manages the authentication state of the user. The <strong>MyApp</strong> struct, representing the entry point of the app, creates an instance of <strong>UserSession</strong> and injects it into the environment. <strong>RootView</strong>, and any other view in the app, can access <strong>userSession</strong> directly from the environment using <strong>@EnvironmentObject</strong>. This pattern is particularly effective for state that needs to be globally accessible, like user authentication status, theme settings, or localization preferences.</p><h3><strong>@Binding</strong></h3><p>@Binding in SwiftUI enables views to share and mutate state interactively without owning it. This is particularly useful in custom, reusable components or complex UI interactions where the state is managed by parent views or external sources. An advanced use of @Binding often involves indirect or conditional state manipulation, or integration with more complex SwiftUI features.</p><p>Now lets look at a bit more advanced stuff, underlying mechanism.</p><p><strong>Underlying Mechanism</strong></p><ul><li>@Binding in SwiftUI creates a two-way connection between a property that stores data and a view that needs to modify that data without owning it. Essentially, it creates a reference to a mutable value.</li><li>The primary role of @Binding is to facilitate communication between parent and child views, allowing child views to update data owned by the parent.</li></ul><p><strong>Data Flow and Updates</strong></p><ul><li>Internally, when you create a @Binding to a property (typically marked with @State in a parent view), SwiftUI creates a direct link to that property. This link is not a copy of the data but a reference to the original source.</li><li>When the bound property is modified through @Binding, SwiftUI updates the original source of the data. Conversely, if the source data changes (e.g., the @State variable in the parent view), the change is automatically reflected in all views that have a @Binding to that data.</li><li>This two-way data binding is key for interactive UI components, such as form inputs, sliders, and switches, where the user’s input needs to modify the app’s state.</li></ul><p><strong>Efficient State Management</strong></p><ul><li>The efficiency of @Binding comes from its ability to update only the necessary parts of the view hierarchy. When a @Binding-connected property changes, only the views that depend on that property are re-rendered.</li><li>SwiftUI’s optimization ensures that using @Binding doesn’t lead to unnecessary view updates or performance overhead. The framework’s diffing algorithm detects the smallest changes in the view hierarchy and updates the UI accordingly.</li></ul><p><strong>Example</strong></p><pre> import SwiftUI<br><br>struct CustomSlider: View {<br>    @Binding var value: Double<br>    var range: ClosedRange&lt;Double&gt;<br>    var step: Double<br><br>    var body: some View {<br>        Slider(value: $value, in: range, step: step)<br>            .accentColor(value &gt; range.upperBound * 0.75 ? .red : .blue)<br>            .onChange(of: value) { newValue in<br>                // more logic can be added here like analytics tracking or conditional actions<br>                performAdditionalActionIfNeeded(for: newValue)<br>            }<br>    }<br><br>    private func performAdditionalActionIfNeeded(for newValue: Double) {<br>        //  logic based on the new value<br>    }<br>}<br><br>struct SettingsView: View {<br>    @State private var sliderValue: Double = 50<br><br>    var body: some View {<br>        CustomSlider(value: $sliderValue, range: 0...100, step: 1)<br>    }<br>}</pre><p>Basically in this example, <strong>CustomSlider</strong> is a reusable component that takes a <strong>@Binding</strong> to a <strong>Double</strong> value. It not only displays the value as a slider but also changes its color based on the value and performs additional actions on value change. The <strong>onChange</strong> modifier is used to trigger a function whenever the slider’s value changes, allowing for the execution of complex logic, such as triggering analytics events or conditional actions. The <strong>@Binding</strong> allows <strong>CustomSlider</strong> to remain generic and reusable, as it doesn’t manage the state itself but interacts with it, making the component flexible and adaptable for different scenarios.</p><h3><strong>Can’t Decide Between @StateObject and @ObservedObject?</strong></h3><p>Choosing between @StateObject and @ObservedObject can sometimes be hard I know.. been there! Especially in complex SwiftUI applications. Let’s break down the decision-making process with some key points and a example:</p><p><strong>When You Might Feel Indecisive</strong></p><ul><li>When you have a view model that seems to fit both wrappers.</li><li>If the ownership of the view model is not clear-cut.</li><li>In scenarios where both a parent and child view interact with the same object.</li></ul><p><strong>Differences Between @StateObject and @ObservedObject</strong></p><ul><li>Ownership and Lifecycle: @StateObject is used when the view owns and initializes the object, ensuring it survives across the view’s lifecycle. @ObservedObject, in contrast, is for when the object is owned elsewhere and the view is just observing it.</li><li>Creation and Destruction: With @StateObject, the SwiftUI view is responsible for creating and destroying the object. @ObservedObject does not have this responsibility.</li></ul><p><strong>Which One to Use?</strong></p><ul><li>Use @StateObject when the view is the source of truth for the object. This is common in standalone views or top-level views in a hierarchy.</li><li>Opt for @ObservedObject when the object is passed down from a parent view or shared across multiple views.</li></ul><p><strong>And example that can show a differentiation scenario:</strong></p><p>Consider a music player app with a <strong>PlayerViewModel</strong> handling playback. There’s a <strong>PlaylistView</strong> displaying a list of tracks and a <strong>NowPlayingView</strong> showing the current track’s details.</p><pre>class PlayerViewModel: ObservableObject {<br>    @Published var currentTrack: Track<br>    // Playback logic here<br>}<br><br>struct PlaylistView: View {<br>    @StateObject var playerViewModel = PlayerViewModel()<br><br>    var body: some View {<br><br>        // List of tracks<br>        // Selecting a track updates playerViewModel.currentTrack<br>        NowPlayingView(playerViewModel: playerViewModel)<br>    }<br>}<br><br>struct NowPlayingView: View {<br>    @ObservedObject var playerViewModel: PlayerViewModel<br><br>    var body: some View {<br>        // Displays details of the currently playing track<br>        // Observes changes to playerViewModel.currentTrack<br>    }<br>}</pre><p>In this case, <strong>PlaylistView</strong> is the primary user of <strong>PlayerViewModel</strong>, so it uses <strong>@StateObject</strong> to own and manage the <strong>PlayerViewModel</strong>. <strong>NowPlayingView</strong>, a child view, just needs to observe and react to changes in the current track, so it uses <strong>@ObservedObject</strong> to refer to the playerViewModel passed down from <strong>PlaylistView</strong>.</p><h4><strong>Conclusion time</strong></h4><p>That was basically it from what i had to tell! I hope it helped you understand state management more. Stay tuned for next one!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCcLkWo2ZcUexhIg9cKWCw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3816d804477e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI VS Jetpack Compose]]></title>
            <link>https://medium.com/@canakyildz/swiftui-vs-jetpack-compose-7b716672b44b?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b716672b44b</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[developer-career]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 08:57:09 GMT</pubDate>
            <atom:updated>2023-11-29T09:18:04.124Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gM3m9TuVkWJvV1VPloaNnA.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Hey there, fellow tech enthusiasts! 👋</p><p>Today I’ve decided to talk about two of the most preferred mobile development frameworks: SwiftUI for iOS and Jetpack Compose for Android. I will be showing some implementation examples, comparisons and talk about both frameworks as overall topics.</p><p>Now, you might be wondering, “Why should I care about this comparison?” if you don’t have a direct purpose of clicking on this article.It has a few reasons why someone might need this article such as deciding which app development path to stroll down, itching to add some nifty new skills to your developer toolkit (which was my intention), or just plain curious about what’s buzzing in the tech world.</p><p>In the next section, I’d like to mention some of the advantages one has over the other. According to my research and overall experience of course.</p><h3><strong>Industrial yet? Easily adaptable?.. : SwiftUI vs. Jetpack Compose</strong></h3><p>Let’s get real about SwiftUI and Jetpack Compose. You know, the stuff they don’t always tell you in the fancy tech blogs.</p><p><strong>SwiftUI: Early Bird Gets the Worm, But…</strong></p><ul><li><strong>Apple Jumped in Early:</strong> Apple dropped SwiftUI in 2019 and was like, “Here, try this.” It gave them a head start, sure, but it also meant we iOS developers had to rewire our brains from UIKit to SwiftUI. And let me tell you, it wasn’t a walk in the park.</li><li><strong>The SwiftUI Learning Curve:</strong> If you’re an iOS dev, moving to SwiftUI can feel like learning to ride a bike all over again. Sure, it’s cool and sleek, but expect some bumps along the road.</li><li><strong>Personal experience:</strong> As a guy who was developing apps with UIKit, transition to SwiftUI was a lazy, curvy and challenging to me. I always procrastinated and kept on delaying it. You need to keep in mind changes in development land happens a lot and you need to keep up indeed. However it’s good to know that something is ready for industry or not. SwiftUI was NOT ready in my opinion till about 2021–2022.</li></ul><p><strong>Jetpack Compose: Late to the Party, But Dances Better?</strong></p><ul><li><strong>Google Playing Catch-Up:</strong> Compose popped up officially in 2021, two years after SwiftUI. It’s like Google saw Apple and said, “Hold my beer.”</li><li><strong>Kotlin to the Rescue:</strong> The good thing? If you’re an Android dev used to Kotlin, jumping into Compose feels more like a small hop than a giant leap. Kotlin’s patterns and syntax fit into Compose like a glove, making the transition smoother than what we iOS folks had with SwiftUI.</li></ul><p><strong>So, What’s the Bottom Line?</strong></p><ul><li><strong>Getting Used to It:</strong> Whether you’re team SwiftUI or team Compose, the start can be rocky. But once you get the hang of it, it’s pretty sweet how fast you can get things done.</li><li><strong>Community and Help:</strong> SwiftUI’s got more road under its belt, so there’s more help out there if you get stuck. Compose is younger, but it’s backed up by the whole Android gang, so you’re not alone.</li></ul><p>By 2023 December, as a person who is developing mainly iOS apps but have been on both ends, I could say both of the frameworks are 99% industrial and are used in a lot of projects. From small to big. Modular or not modular. White-label or one brand.</p><h3><strong>Architectural Principles</strong></h3><h4><strong>SwiftUI Architecture</strong></h4><ul><li><strong>Declarative Syntax Example</strong>:</li></ul><p>This code snippet creates a text element, styles it, and adds padding, all in a straightforward, readable manner.</p><pre>Text(&quot;Hello, World!&quot;)<br>  .font(.title)<br>  .padding()</pre><ul><li><strong>Data Binding</strong>: Uses properties like <strong>@State</strong> for dynamic data updates.</li></ul><p>Here, any changes to ‘name’ automatically update the TextField.</p><pre>@State private var name: String = &quot;&quot;<br>TextField(&quot;Enter your name&quot;, text: $name)</pre><ul><li><strong>View Composition</strong>: Combines smaller views to create complex UIs.</li></ul><p><strong>VStack</strong> stacks the text views vertically.</p><pre>VStack {<br>  Text(&quot;Welcome&quot;)<br>  Text(&quot;SwiftUI&quot;)<br>}</pre><h4><strong>Jetpack Compose Architecture</strong></h4><ul><li><strong>Declarative UI Example</strong>:</li></ul><p>Similar to SwiftUI, this Compose code creates a text element with padding.</p><pre>Text(&quot;Hello, Android!&quot;, modifier = Modifier.padding(16.dp))</pre><ul><li><strong>State Management</strong>: Implements state hoisting for better control.</li></ul><p>Changes to ‘name’ reflect in the TextField.</p><pre>var name by remember { mutableStateOf(&quot;&quot;) }<br>TextField(value = name, onValueChange = { name = it })</pre><ul><li><strong>Composable Functions</strong>: Build UI components as reusable functions.</li></ul><p><strong>Greeting</strong> is a reusable component that displays a greeting message.</p><pre>@Composable<br>fun Greeting(name: String) {<br>  Text(text = &quot;Hello, $name!&quot;)<br>}</pre><p><strong>Comparison</strong></p><ul><li><strong>State Management</strong>: SwiftUI uses <strong>@State</strong>, while Jetpack Compose uses <strong>remember</strong> and <strong>mutableStateOf</strong> for state handling.</li><li><strong>Syntax and Structure</strong>: Both use a similar declarative style, but with different syntax — Swift for SwiftUI and Kotlin for Compose.</li><li><strong>Interoperability with Older Frameworks</strong>: Jetpack Compose more easily integrates with existing Android views compared to SwiftUI’s integration with UIKit.</li></ul><p>Next, we’ll see how these principles play out in real-world development scenarios.</p><h3><strong>Development Experience</strong></h3><h4><strong>SwiftUI Development Experience</strong></h4><ul><li><strong>Building UI Elements</strong>:</li></ul><p>Here, creating a toggle switch in SwiftUI is intuitive. Just a few lines of code and you have a functional toggle with a label.</p><pre>Toggle(isOn: $isToggled) {<br>    Text(&quot;Switch this toggle&quot;)<br>}</pre><ul><li><strong>Data-Driven Views</strong>: SwiftUI’s strong suit is creating data-driven views that automatically update with state changes. This makes it easier to build dynamic and interactive apps.</li><li><strong>Swift Integration</strong>: Leveraging Swift’s modern features, developers can create complex functionalities with less code and greater efficiency.</li></ul><h4><strong>Jetpack Compose Development Experience</strong></h4><ul><li><strong>Constructing UI Components</strong>:</li></ul><pre>Checkbox(<br>    checked = isChecked,<br>    onCheckedChange = { isChecked = it }<br>)</pre><ul><li>Similar to SwiftUI, Jetpack Compose simplifies UI creation. This snippet shows how to implement a checkbox with state handling.</li><li><strong>Reactive UI Updates</strong>: Jetpack Compose excels in building reactive UIs that reflect changes in data states or user interactions seamlessly.</li><li><strong>Kotlin Features</strong>: Utilizes Kotlin’s capabilities like extension functions and higher-order functions, enabling more expressive and concise code.</li></ul><p><strong>Comparison</strong></p><ul><li><strong>Developer Productivity</strong>: Both frameworks significantly reduce the boilerplate code required for UI design, enhancing developer productivity.</li><li><strong>Learning Curve</strong>: SwiftUI’s integration with other Apple technologies might require a learning period for developers new to Apple’s ecosystem, whereas Jetpack Compose’s similarity to traditional Android development can be more approachable for Android developers.</li><li><strong>Tooling and Ecosystem</strong>: SwiftUI benefits from the mature ecosystem of Xcode and Apple’s development tools. Jetpack Compose, though newer, is rapidly growing and integrating within Android Studio, offering robust tools and features for Android app development.</li></ul><h3><strong>Example feature: User Profile Display</strong></h3><p><strong>Feature Description: </strong>Displaying a user profile with a name and an “Update” button that changes the name.</p><h4><strong>SwiftUI</strong></h4><pre>struct UserProfileView: View {<br>    @State private var userName: String = &quot;John Doe&quot;<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;User: \(userName)&quot;)<br>                .font(.title)<br>            Button(&quot;Update&quot;) {<br>                self.userName = &quot;Jane Doe&quot;<br>            }<br>            .padding()<br>            .background(Color.blue)<br>            .foregroundColor(.white)<br>            .cornerRadius(10)<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li><strong>@State</strong> manages the <strong>userName</strong> state.</li><li>The <strong>Text</strong> view displays the current user name.</li><li>The <strong>Button</strong> view updates <strong>userName</strong> when clicked.</li></ul><h4><strong>Jetpack Compose</strong></h4><pre>@Composable<br>fun UserProfile() {<br>    var userName by remember { mutableStateOf(&quot;John Doe&quot;) }<br><br>    Column {<br>        Text(&quot;User: $userName&quot;, style = MaterialTheme.typography.h6)<br>        Button(onClick = { userName = &quot;Jane Doe&quot; }) {<br>            Text(&quot;Update&quot;)<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li><strong>remember</strong> and <strong>mutableStateOf</strong> handle the <strong>userName</strong> state.</li><li>The <strong>Text</strong> composable shows the user name.</li><li>The <strong>Button</strong> composable changes <strong>userName</strong> on click.</li></ul><h4><strong>Comparison:</strong></h4><ul><li><strong>State Management</strong>: SwiftUI uses <strong>@State</strong>, Jetpack Compose uses <strong>remember</strong> and <strong>mutableStateOf</strong>.</li><li><strong>UI Elements</strong>: Both frameworks offer a clear, concise way to create UI elements like text and buttons.</li><li><strong>Data Binding</strong>: Both update the UI reactively based on user interactions.</li></ul><h3><strong>Career choice</strong></h3><p>I’m not here to tell you go with this or that. It’s all preferences, industry needs and overall need for developers. Tomorrow AI might replace all of us so this article might no longer be in need. Or next year apple might buy google or some chaotic stuff like this. That I can’t predict but;</p><p>You might be saying that you are new to all of this, what to go with? Well. iOS Apps are natively developed on apple’s operating systems. You will need a MacBook. But on android development you dont have that issue. Matter fact, google might be playing the game ahead with their Multiplatform which allows developers to write multi platform apps. This is critical. Because Apple is late to the party. Actually there is a nice article id like to refer on this:</p><p><a href="https://betterprogramming.pub/kmp-cm-apples-strategic-failure-cb758c24f824"><strong><em>Apple’s Strategic failure by Michael Long</em></strong></a></p><h3><strong>Personal Experience and Opinion</strong></h3><p>Now, let’s get personal for a moment. My journey with SwiftUI has been nothing short of exciting. The moment I dived into SwiftUI, I felt like a whole new world of possibilities opened up. The declarative syntax wasn’t just a breath of fresh air; it was a gust of fresh innovation. Building UIs became more intuitive, almost like sketching out my thoughts directly into code. The real-time previews? A game-changer for me. They transformed the way I approached UI design, allowing me to see the impact of my code instantly.</p><p>As for Jetpack Compose, even though I haven’t worked with it as extensively as SwiftUI, my exploration into it has left me genuinely impressed. Its approach to simplifying UI design on Android mirrors many of the reasons I appreciate SwiftUI. From what I’ve seen and read, Compose is making Android development more accessible and enjoyable, much like SwiftUI has done for iOS.</p><p>Here’s the thing: I’m an iOS guy through and through. But that doesn’t stop me from admiring what’s happening on the other side of the fence. Jetpack Compose, from my perspective, is a sign that the entire mobile development landscape is moving in a fantastic direction with the Multiplatform that they introduced which Apple doesn’t have yet.</p><p>In conclusion, SwiftUI has reshaped my iOS development experience, making it more streamlined and enjoyable. And from my brief encounters and observations of Jetpack Compose, I can say it’s doing the same for the Android world. Both are powerful tools that are pushing the boundaries of what we can achieve in mobile app development, and I can’t wait to see where they take us next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FUmGrILEnYk0pmxoMcIEg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b716672b44b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shifting to Server side: Swift + Node.JS]]></title>
            <link>https://medium.com/@canakyildz/shifting-to-server-side-swift-node-js-ea94c0035998?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea94c0035998</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 16:22:41 GMT</pubDate>
            <atom:updated>2023-11-29T09:15:00.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CmCDHolZATWwNxE4uBYgw.jpeg" /></figure><p>If you are building an application that will have other people in usage, at some point your system will require decisions to make that can profoundly affect your application’s performance, security, and scalability and question of <em>where to place your application logic</em> arises: on the client-side or the server-side. Understanding this choice is vital for both burgeoning startups and established enterprises.</p><h3><strong>Real life needs</strong></h3><p>When I was building my project Hustler Engine, i was using bunch of different providers and services. Most of them were integrated through API calls. And first issue i noticed was that, if someone uses the app for a while and tracks each call on a tool like Proxyman, then my whole set up is exposed besides the unique AI model work we did. From provider names to request bodies with sensitive or very exposing information. So I got my hosting on Vercel, started learning node.js and built my functions. The information needed from database to work with client content was no longer exposed on requests but were handled on backend mostly.</p><p>Another case i came across while building my latest project Hustler Engine, i thought that including user id or any unique sensitive id in the api calls is a dangerous sport. I initialized Firebase auth in my Node.js code and communicated but also checked user authentication on api calls with JWT token in each call which is one time only token that helps with secure communication with backend.</p><p>Or forget about my own project but consider a social media app like Instagram: initially, it may handle image processing and basic functionalities on the user’s device (client-side). However, as the app grows in popularity, the need for more sophisticated features, better performance, and enhanced security necessitates a shift to server-side processing. This transition allows for advanced image processing algorithms, better handling of user data, and more efficient content delivery to a global audience.</p><p>Similarly, a small e-commerce platform might start by managing its product catalog and transactions on the client-side. But as its customer base expands, moving these functionalities to the server-side enables better inventory management, personalized user experiences, and robust security measures against fraud.</p><h3><strong>When to start moving to server side?</strong></h3><p>The decision to shift from client-side to server-side processing typically arises under several circumstances:</p><ul><li><strong>Increasing Complexity</strong>: As the application’s features and functionalities become more complex, the client-side approach may no longer be efficient or feasible. Server-side processing can handle this complexity more effectively.</li><li><strong>Enhanced Security Needs</strong>: When dealing with sensitive user data or when the risk of cyber threats increases, server-side processing offers a more secure environment, as it’s harder for attackers to access the backend directly.</li><li><strong>Scalability Concerns</strong>: For applications expecting a surge in user numbers or data volume, server-side processing provides better scalability options, accommodating growth without degrading performance.</li><li><strong>Performance Optimization</strong>: When the application begins to suffer from latency or performance issues due to heavy client-side processing, transitioning to the server-side can significantly improve user experience.</li><li><strong>Regulatory Compliance</strong>: Certain industries require strict data handling and privacy standards (like GDPR in Europe). Server-side processing often makes it easier to comply with these regulations.</li></ul><h3>Action 🎥</h3><p>In this article, we will explore these considerations through a practical scenario involving a mobile app developed with SwiftUI. Starting with client-side logic for a feedback feature, we’ll journey through its evolution and eventual transition to server-side processing with Node.js, highlighting the challenges and solutions at each step. Whether you’re developing a new app or looking to optimize an existing one, understanding this transition is key to creating robust, efficient, and scalable software solutions.”</p><h4>Client-Side Only Implementation: Starting Simple</h4><p>Our journey begins with a SwiftUI app designed to collect user feedback. The feature is straightforward: users submit their feedback through a form, and the app categorizes this feedback before sending it to the server.</p><p><strong>The SwiftUI Feedback Form</strong></p><p>We implemented a user-friendly feedback form in SwiftUI. Users can type their comments or issues, and upon submission, the app categorizes the feedback as a bug report, feature request, or general feedback. This categorization is based on keywords found in the user’s input.</p><pre>import SwiftUI<br><br>struct FeedbackView: View {<br>    @State private var feedbackText = &quot;&quot;<br>    @State private var isSubmitting = false<br><br>    var body: some View {<br>        NavigationView {<br>            Form {<br>                Section(header: Text(&quot;Your Feedback&quot;)) {<br>                    TextEditor(text: $feedbackText)<br>                        .frame(height: 200)<br>                }<br>                <br>                Section {<br>                    Button(action: submitFeedback) {<br>                        Text(isSubmitting ? &quot;Submitting...&quot; : &quot;Submit&quot;)<br>                    }.disabled(feedbackText.isEmpty || isSubmitting)<br>                }<br>            }<br>            .navigationBarTitle(&quot;Feedback&quot;)<br>        }<br>    }<br><br>    func submitFeedback() {<br>        isSubmitting = true<br>        APIService.submitFeedback(feedback: feedbackText) { success in<br>            isSubmitting = false<br>            if success {<br>                // Handle successful submission, like showing an alert<br>                feedbackText = &quot;&quot; // Resetting text<br>            } else {<br>                // Handle failure<br>            }<br>        }<br>    }<br>}</pre><p><strong>The APIService Class</strong></p><p>The heart of our client-side logic lies in the <strong>APIService</strong> class. This class handles the network request, including the feedback text, its categorization, and flags for notifying different teams. The logic, written in Swift, looks something like this:</p><pre>import Foundation<br><br>class APIService {<br>    static func submitFeedback(feedback: String, completion: @escaping (Bool) -&gt; Void) {<br>        guard let url = URL(string: &quot;https://example/api/feedback&quot;) else {<br>            completion(false)<br>            return<br>        }<br><br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br><br>        let body: [String: Any] = [<br>            &quot;feedback&quot;: feedback,<br>            &quot;category&quot;: categorizeFeedback(feedback),<br>            &quot;shouldNotifyDevelopmentTeam&quot;: feedback.lowercased().contains(&quot;bug&quot;),<br>            &quot;shouldNotifyProductTeam&quot;: feedback.lowercased().contains(&quot;feature&quot;)<br>        ]<br><br>        request.httpBody = try? JSONSerialization.data(withJSONObject: body)<br><br>        URLSession.shared.dataTask(with: request) { _, response, error in<br>            DispatchQueue.main.async {<br>                completion(error == nil &amp;&amp; (response as? HTTPURLResponse)?.statusCode == 200)<br>            }<br>        }.resume()<br>    }<br><br>    private static func categorizeFeedback(_ feedback: String) -&gt; String {<br>        if feedback.lowercased().contains(&quot;bug&quot;) {<br>            return &quot;bug report&quot;<br>        } else if feedback.lowercased().contains(&quot;feature&quot;) {<br>            return &quot;feature request&quot;<br>        } else {<br>            return &quot;general feedback&quot;<br>        }<br>    }<br>}</pre><h3>The Shift to Server-Side: Embracing Complexity and Security</h3><p>When feeling like the feedback feature is starting to strain under the weight of its client-side implementation. This is especially true as the feedback we receive becomes more varied and complex. To address this, we transition to server-side processing using Node.js, a JavaScript runtime that’s efficient and great for handling JSON-based client-server communication. This move enables us to manage more complex logic, enhance security, and centralize updates and maintenance.</p><h4>Node.js to the Rescue</h4><p>We’ve chosen Node.js for our server-side logic. Here’s how we implement the feedback categorization and notification logic:</p><h4>Step 1: Setting Up the Environment</h4><ul><li>Install Node.js and npm (Node Package Manager) on your system.</li><li>Initialize a new Node.js project with <strong>npm init </strong>in your project directory.</li></ul><h4>Step 2: Installing Dependencies</h4><ul><li>Use npm to install Express.js (npm install express), a web application framework for Node.js.</li><li>Install the body-parser middleware (npm install body-parser) for handling JSON requests.</li></ul><h4>Step 3: Building the Server Logic</h4><p>1. Import Libraries: Start by requiring Express and body-parser in your main server file (<strong><em>‘server.js’</em></strong>).</p><pre>const express = require(&#39;express&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const app = express();<br>app.use(bodyParser.json());</pre><p>2. Define Utility Functions:</p><ul><li>Categorize Feedback: Create a function to categorize the feedback based on keywords. Think of it like a Swift function that takes a string and returns a specific output based on its content.</li><li>Log Feedback: A simple function to log feedback, akin to printing to the console in Swift.</li><li>Trigger Notifications: Depending on the feedback category, this function decides which team to notify.</li></ul><p>3. Handle POST Requests:</p><p>Set up an endpoint (‘<strong>/api/feedback’</strong>) to receive POST requests.</p><ul><li>Use the defined functions to process and categorize the incoming feedback.</li><li>Respond to the client with a confirmation message.</li></ul><p>4. Start the Server:</p><ul><li>Listen on a specified port, just as you would set up a listener for network requests in an iOS app.</li></ul><h4>Step 4: Testing and Debugging</h4><ul><li>Test the server using tools like Postman.</li><li>Debug using console logs, similar to using print statements in Swift.</li></ul><pre>const express = require(&#39;express&#39;);<br>const axios = require(&#39;axios&#39;);<br>const app = express();<br><br>app.use(express.json());<br><br>// Endpoint to receive feedback from the client<br>app.post(&#39;/submit-feedback&#39;, async (req, res) =&gt; {<br>    try {<br>        const feedback = req.body.feedback;<br>        const categorizedFeedback = categorizeFeedback(feedback);<br><br>        // Construct the request body<br>        const requestBody = {<br>            feedback: feedback,<br>            category: categorizedFeedback,<br>            shouldNotifyDevelopmentTeam: feedback.toLowerCase().includes(&#39;bug&#39;),<br>            shouldNotifyProductTeam: feedback.toLowerCase().includes(&#39;feature&#39;)<br>        };<br><br>        // Send the feedback to the external database server that we were<br>        // initially sending information from our Swift code <br>        const response = await axios.post(&#39;https://example-db-server.com/api/feedback&#39;, requestBody);<br><br>        // Check if the request was successful<br>        if (response.status === 200) {<br>            res.status(200).send(&#39;Feedback submitted successfully&#39;);<br>        } else {<br>            res.status(500).send(&#39;Error submitting feedback&#39;);<br>        }<br>    } catch (error) {<br>        res.status(500).send(&#39;Error submitting feedback&#39;);<br>    }<br>});<br><br>// Function to categorize feedback<br>function categorizeFeedback(feedback) {<br>    if (feedback.toLowerCase().includes(&#39;bug&#39;)) {<br>        return &#39;bug report&#39;;<br>    } else if (feedback.toLowerCase().includes(&#39;feature&#39;)) {<br>        return &#39;feature request&#39;;<br>    } else {<br>        return &#39;general feedback&#39;;<br>    }<br>}<br><br>// Start the server<br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br>    console.log(`Server running on port ${PORT}`);<br>});</pre><p>This server-side logic categorizes the feedback and decides whether to notify the development team or the product team. Obviously in our case and example — it’s just to demonstrate that we can move our client side logic to server side with ease. But if you were to build such functionality, there would be a database that backend connects with and from there gathering issue tickets or whatever the feature is.</p><p><strong>The Simplified Client</strong></p><p>With the shift of complex logic to the server, our SwiftUI <strong>APIService</strong> becomes simpler and more focused on just sending the feedback:</p><pre>class APIService {<br>    static func submitFeedback(feedback: String, completion: @escaping (Bool) -&gt; Void) {<br>        // Update the URL to point to your Node.js server endpoint<br>        guard let url = URL(string: &quot;http://your-node-js-server.com/submit-feedback&quot;) else {<br>            completion(false)<br>            return<br>        }<br><br>        var request = URLRequest(url: url)<br>        request.httpMethod = &quot;POST&quot;<br>        request.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br><br>        // Body now only needs the feedback text<br>        let body: [String: Any] = [&quot;feedback&quot;: feedback]<br><br>        request.httpBody = try? JSONSerialization.data(withJSONObject: body)<br><br>        URLSession.shared.dataTask(with: request) { _, response, error in<br>            DispatchQueue.main.async {<br>                completion(error == nil &amp;&amp; (response as? HTTPURLResponse)?.statusCode == 200)<br>            }<br>        }.resume()<br>    }<br>}</pre><h3>The Ending and Idealogy : A Balanced Approach</h3><p>This article shows a basic level demonstration of shifting from client to server side; importance of balancing client-side and server-side logic in app development. While starting with client-side processing is simple and straightforward, as complexity and security needs grow, moving to server-side processing becomes inevitable. This not only enhances the efficiency and security of the app but also makes it more scalable and easier to maintain. Remember, the key is to assess your application’s needs continuously and be ready to adapt your architecture accordingly.</p><p><strong>Key Differences</strong></p><ul><li><strong>Complexity</strong>: The client-side logic (before moving to the backend) is more complex as it includes categorization and decision-making regarding notifications. After moving to the backend, this complexity is shifted to the server, simplifying the client-side code.</li><li><strong>Scalability and Maintainability</strong>: Handling such logic on the server side makes the application more scalable and maintainable. It centralizes the business logic, making it easier to update and manage.</li><li><strong>Security and Performance</strong>: Offloading processing to the server can enhance security and performance. It prevents exposing business logic details to the client and reduces the processing load on the client side.</li></ul><p>Thanks for reading my article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-b5Gd6eL2m2tnVFYf8FMg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea94c0035998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Combine + Async/Await (Basics)]]></title>
            <link>https://medium.com/@canakyildz/combine-async-await-basics-3d4746f31698?source=rss-25884b2645e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d4746f31698</guid>
            <dc:creator><![CDATA[Can Akyıldız]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 20:18:49 GMT</pubDate>
            <atom:updated>2023-11-29T09:12:24.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNbr8SpWFcJdkG13kWTHfg.jpeg" /></figure><p>Hey friends! It’s been a while since I have written an article but I said it’s time!! I’ve decided to write my articles on Medium joining rest of the community. I’m a bit rusty with writing articles but I tried my best down below! Don’t worry I got you!!</p><p>Today, we’re going on an adventure in the world of Swift’s asynchronous programming, this one will be more likely basics and we will be exploring two cool tools: Combine and Async/Await. Imagine them as our coding buddies helping us build a fantastic weather app that works smoothly!</p><p>In our exploration through 3 different levels of complexity, we are architects of an app that fetches and displays weather information. Our blueprint is thoughtfully designed to capture the synergy of Async/Await and Combine, showing you their collaborative elegance.</p><h3><strong>Level 1: Real Basics</strong></h3><p>In this level, we will create a basic view model and SwiftUI view to be working together to populate data asynchronously and reactively.</p><p><strong>Step 1: Creating the View Model</strong></p><p>Alright, so the View Model is like the brain of our operation. It’s busy in the background, grabbing the weather info and getting it ready for display.</p><pre>import Combine<br><br>class WeatherViewModel: ObservableObject {<br>    @Published var weatherData: WeatherData?<br>    private var cancellables: Set&lt;AnyCancellable&gt; = []<br>    <br>    func fetchWeather() {<br>        getWeatherData()<br>            .receive(on: DispatchQueue.main)<br>            .sink(receiveCompletion: { _ in },<br>                  receiveValue: { data in<br>                      self.weatherData = data<br>                  })<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    private func getWeatherData() -&gt; Future&lt;WeatherData, Error&gt; {<br>        return Future { promise in<br>            async {<br>                do {<br>                    let data = try await self.downloadWeatherData()<br>                    promise(.success(data))<br>                } catch {<br>                    promise(.failure(error))<br>                }<br>            }<br>        }<br>    }<br>    <br>    private func downloadWeatherData() async throws -&gt; WeatherData {<br>        // Implementation of data fetching here<br>    }<br>}</pre><p>Here’s a quick peek at what’s happening:</p><ul><li>The View Model is keeping an eye on weather data. Whenever the data changes, it makes sure the display gets updated. Pretty neat, huh?</li><li><strong>@Published var weatherData</strong>: A beacon. Whenever <strong>weatherData</strong> changes, it emits signals, keeping the UI synchronized.</li><li><strong>func fetchWeather()</strong>: The conductor. It summons <strong>getWeatherData</strong>, coordinating the flow of data and ensuring it reaches the UI on the main stage.</li><li><strong>getWeatherData() -&gt; Future&lt;WeatherData, Error&gt;</strong>: A promise of weather data. It uses Async/Await to fetch the data, wrapping it in Combine’s <strong>Future</strong> to harmonize with our data flow.</li></ul><p><strong>Step 2: Creating the SwiftUI View</strong></p><p>The view is our canvas where user interactions and UI unfold. It listens to the ViewModel, rendering the user experience.</p><pre>import SwiftUI<br><br>struct WeatherView: View {<br>    @ObservedObject var viewModel = WeatherViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            if let weather = viewModel.weatherData {<br>                Text(&quot;Weather: \(weather.description)&quot;)<br>            } else {<br>                Text(&quot;Loading...&quot;)<br>            }<br>            <br>            Button(&quot;Refresh&quot;) {<br>                viewModel.fetchWeather()<br>            }<br>        }<br>    }<br>}</pre><p>Explanation:</p><ul><li><strong>@ObservedObject var viewModel</strong>: The view’s ear to the ViewModel. It listens for changes, ensuring the UI reacts in harmony with the data.</li><li><strong>if let weather = viewModel.weatherData</strong>: A responsive expression. It adapts the UI based on the availability of weather data, ensuring an accurate portrayal of the current state.</li><li><strong>Button(“Refresh”)</strong>: An interactive element. It invokes <strong>fetchWeather</strong>, cueing the ViewModel to refresh the data.</li></ul><p>In simple words, the view keeps an ear out for changes in the View Model, making sure that the display matches the latest info.</p><h3><strong>LEVEL 2: Adding More Goodies (Forecast Details </strong>📅<strong>)</strong></h3><p>Now that we’ve got the basics, let’s sprinkle in some extra features! We’re going to add a forecast for the next seven days.</p><p><strong>Step 1: Updating the view model</strong></p><p>We’re going to teach our View Model some new tricks, like handling weather forecasts for an entire week!</p><pre>import Combine<br><br>class WeatherViewModel: ObservableObject {<br>    @Published var dailyForecasts: [DailyForecast] = []<br>    @Published var selectedDayForecast: DailyForecast?<br>    private var cancellables: Set&lt;AnyCancellable&gt; = []<br>    <br>    // Function to fetch weekly weather forecasts<br>    func fetchWeeklyForecasts() {<br>        getWeeklyForecasts()<br>            .receive(on: DispatchQueue.main)<br>            .sink(receiveCompletion: { _ in },<br>                  receiveValue: { forecasts in<br>                      self.dailyForecasts = forecasts<br>                  })<br>            .store(in: &amp;cancellables)<br>    }<br>    <br>    private func getWeeklyForecasts() -&gt; Future&lt;[DailyForecast], Error&gt; {<br>        return Future { promise in<br>            async {<br>                do {<br>                    let forecasts = try await self.downloadWeeklyForecasts()<br>                    promise(.success(forecasts))<br>                } catch {<br>                    promise(.failure(error))<br>                }<br>            }<br>        }<br>    }<br>    <br>    private func downloadWeeklyForecasts() async throws -&gt; [DailyForecast] {<br>        // Implementation details here to fetch forecast data<br>    }<br>    <br>    // Function to handle day selection and fetch detailed weather information<br>    func selectDay(_ day: DailyForecast) {<br>        selectedDayForecast = day<br>        // Additional logic can be added here to fetch more details if necessary<br>    }<br>}</pre><p><strong>Step 2: Updating the View w/ Adding Forecast Selection</strong></p><p>We’ll update our view to list the daily forecasts and handle user interactions for selecting a day.</p><pre>import SwiftUI<br><br>struct WeatherView: View {<br>    @ObservedObject var viewModel = WeatherViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            List(viewModel.dailyForecasts) { day in<br>                HStack {<br>                    Text(day.date)<br>                    Spacer()<br>                    Text(&quot;\(day.temperature)°&quot;)<br>                }<br>                .contentShape(Rectangle())<br>                .onTapGesture {<br>                    viewModel.selectDay(day)<br>                }<br>            }<br>            <br>            if let selectedDay = viewModel.selectedDayForecast {<br>                Text(&quot;Detailed weather for \(selectedDay.date): \(selectedDay.description)&quot;)<br>            }<br>            <br>            Button(&quot;Refresh&quot;) {<br>                viewModel.fetchWeeklyForecasts()<br>            }<br>        }<br>        .onAppear {<br>            viewModel.fetchWeeklyForecasts()<br>        }<br>    }<br>}</pre><p>What happened here?</p><ul><li><strong>Forecast Fetching:</strong> The ViewModel now harbors the capability to fetch and manage a week’s worth of weather forecasts, harnessing the essence of Async/Await within Combine’s embrace to promise and deliver the fetched data.</li><li><strong>Day Selection:</strong> The structure respects user interaction, allowing the selection of a day to unveil more detailed weather insights. The choice triggers a cascade of updates, utilizing Combine’s reactivity to keep the UI in perfect synchrony with user actions and data changes.</li><li><strong>UI Elevation:</strong> The SwiftUI View blossoms with enhanced functionalities, listening and adapting to the ViewModel’s tales of daily forecasts and selected days. It offers a list of forecasts for interaction and displays detailed weather narratives when a day receives the user’s curiosity.</li></ul><h3><strong>LEVEL 3: Implementing Location Search</strong></h3><p>Time to go big! Let’s make our app even more powerful by letting users search for weather info from different locations.</p><p><strong>Step 1: Updating View Model</strong></p><p>Our ViewModel will now handle location-based queries, managing both current weather information and forecast data intricately.</p><pre>import Combine<br><br>class WeatherViewModel: ObservableObject {<br>    @Published var locationWeather: LocationWeather?<br>    @Published var locationForecasts: [DailyForecast] = []<br>    private var cancellables: Set&lt;AnyCancellable&gt; = []<br>    <br>    func fetchWeather(for location: String) {<br>        async {<br>            do {<br>                let weather = try await self.downloadLocationWeather(for: location)<br>                DispatchQueue.main.async {<br>                    self.locationWeather = weather<br>                }<br>                <br>                self.fetchLocationForecasts(for: location)<br>                    .sink(receiveCompletion: { _ in },<br>                          receiveValue: { forecasts in<br>                              self.locationForecasts = forecasts<br>                          })<br>                    .store(in: &amp;cancellables)<br>                <br>            } catch {<br>                // Handle errors appropriately<br>            }<br>        }<br>    }<br>    <br>    private func fetchLocationForecasts(for location: String) -&gt; AnyPublisher&lt;[DailyForecast], Error&gt; {<br>        // Combine logic here to fetch and manage forecast data<br>    }<br>    <br>    private func downloadLocationWeather(for location: String) async throws -&gt; LocationWeather {<br>        // Async/Await logic here to fetch current location weather<br>    }<br>}</pre><p><strong>Step: 2 Updating SwiftUI View: Incorporating Location Search</strong></p><p>The SwiftUI View will offer an interface for location inputs and display tailored weather information based on the user’s queries.</p><pre>import SwiftUI<br><br>struct WeatherView: View {<br>    @ObservedObject var viewModel = WeatherViewModel()<br>    @State private var locationQuery: String = &quot;&quot;<br>    <br>    var body: some View {<br>        VStack {<br>            TextField(&quot;Enter location&quot;, text: $locationQuery, onCommit: {<br>                viewModel.fetchWeather(for: locationQuery)<br>            })<br>            .textFieldStyle(RoundedBorderTextFieldStyle())<br>            .padding()<br>            <br>            if let weather = viewModel.locationWeather {<br>                Text(&quot;Current weather in \(locationQuery): \(weather.description)&quot;)<br>            }<br>            <br>            List(viewModel.locationForecasts) { forecast in<br>                Text(&quot;Weather on \(forecast.date): \(forecast.description)&quot;)<br>            }<br>            <br>            Button(&quot;Refresh&quot;) {<br>                viewModel.fetchWeather(for: locationQuery)<br>            }<br>        }<br>    }<br>}</pre><p>Detailing the Refinements:</p><ul><li><strong>Location-Based Queries:</strong> The ViewModel now gracefully manages location-based weather inquiries. It fetches and maintains both current weather and forecasts, fostering a versatile and dynamic data flow that adjusts based on user input.</li><li><strong>Unified Fetching:</strong> The ViewModel performs a symphony where Async/Await fetches current weather data while Combine manages the fetching, subscription, and updating of forecast data. This amalgamation ensures an efficient, responsive, and harmonious data flow.</li><li><strong>Interactive UI:</strong> The SwiftUI View invites user interaction, accommodating location inputs, and responding with tailored weather displays. It listens and reacts to the ViewModel’s stories of weather data, ensuring that the user interface remains synchronized and intuitive.</li></ul><h3><strong>The End</strong></h3><p>Throughout our journey of <strong>Basics</strong>, we’ve seen how Combine and Async/Await can work together beautifully in Swift, making our code more powerful and easier to understand. We started simple, fetching weather data and displaying it. Then, we added more features, like showing forecasts and letting users pick locations, making our app more dynamic and useful. Each step showed us how these tools make our app respond smoothly to whatever the user needs or whatever data comes in. In the end, using Combine and Async/Await together helps us write apps that can handle real-world complexity while keeping our code clean and manageable. It’s like having a super team of helpers, making sure our app runs smoothly no matter what!</p><p>Hoping to meet on another article! Stay safe and goood!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr53yGQ2HV7NyjAeImjjuw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d4746f31698" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>