<?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 Ade Adegoke on Medium]]></title>
        <description><![CDATA[Stories by Ade Adegoke on Medium]]></description>
        <link>https://medium.com/@77adekunle?source=rss-3dac943aea19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K5OGbPkvN67tpflXbheQWQ.jpeg</url>
            <title>Stories by Ade Adegoke on Medium</title>
            <link>https://medium.com/@77adekunle?source=rss-3dac943aea19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:46:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@77adekunle/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[Why you can use MVVM with SwiftUI: Debunking the Myth]]></title>
            <link>https://medium.com/@77adekunle/why-you-can-use-mvvm-with-swiftui-debunking-the-myth-cd9d26404cf4?source=rss-3dac943aea19------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9d26404cf4</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ade Adegoke]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 10:29:10 GMT</pubDate>
            <atom:updated>2024-10-25T05:07:30.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lAIUjzvBqTF6E4cO" /><figcaption>Photo by <a href="https://unsplash.com/@guibolduc?utm_source=medium&amp;utm_medium=referral">Guillaume Bolduc</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The main purpose of <strong>MVVM</strong> is to decouple the UI of an application from its business logic. Hence, it will be much easier to develop, test, and maintain the project, and its evolution. Now, with the release of SwiftUI, some engineers say that <strong>MVVM</strong> is redundant because it introduces an additional layer — the ViewModel, which they claim is unnecessary.<br>In this blog, we will take a closer look at some of the anti-arguments for <strong>MVVM</strong> in SwiftUI and provide reasons why it is still valuable based on its purpose. Here are some of the common anti-arguments:</p><h3><strong>1: SwiftUI’s Declarative Nature and Built-in State Management Make a ViewModel Unnecessary</strong></h3><h4>Argument:</h4><p>Some engineers argue that SwiftUI’s declarative approach, especially with property wrappers like @State, @Binding, and @ObservedObject, manages data and state changes directly in the view, making a separate ViewModel unnecessary.</p><h4>Rebuttal:</h4><p>While SwiftUI’s declarative style and property wrappers simplify basic state management, they don’t address the full scope of separation of concerns, particularly in larger, more complex applications. Property wrappers like @State and @Binding are excellent for managing view-specific state but fall short in managing business logic and data transformations, which can end up leaking into the view layer. This leakage leads to harder-to-maintain and test code, especially as the app scales.</p><p><strong>MVVM</strong> ensures a clean separation between UI and business logic. The ViewModel handles all data transformations, logic, and state management, keeping the view solely responsible for UI presentation. This not only promotes code testability but also improves maintainability as applications grow. SwiftUI’s built-in mechanisms do not fully achieve this decoupling, making a ViewModel essential for long-term scalability and clean architecture.</p><p>The main reason for using a ViewModel is that, as applications grow, it becomes harder to maintain code if business logic is mixed with UI code. A ViewModel future-proofs the code by keeping UI and logic separate, which isn’t addressed by SwiftUI’s declarative approach alone.</p><p>Misuse of architectural patterns, such as putting business logic in the wrong layer, often leads to bloated components. When business logic is correctly placed in the <strong>Model</strong>, as it should be in both <strong>MVC</strong> and <strong>MVVM</strong>, the ViewModel may seem redundant for simpler cases. However, for more complex use cases, where data transformation and view-specific state management are necessary, the ViewModel becomes a valuable mediator between the Model and the View.</p><h3>2: Separation of Concerns Can Be Achieved with Other Architectures Like Flux or TCA</h3><h4>Argument:</h4><p>Some suggest that separation of concerns can still be achieved without <strong>MVVM</strong> by organizing logic into models or using alternative architectures like Flux or The Composable Architecture (TCA).</p><h4>Rebuttal:</h4><p>While architectures like Flux and TCA also promote separation of concerns, <strong>MVVM</strong> is a more straightforward and widely adopted pattern, especially in iOS development.<strong> MVVM</strong>’s simplicity, coupled with its focus on testability, makes it ideal for most SwiftUI apps. More complex architectures like TCA introduce significant boilerplate and steep learning curves. For most software engineers, <strong>MVVM</strong> strikes the right balance between simplicity and structure, allowing for easy testing and maintenance without introducing additional complexity.</p><h3>3: <strong>MVVM Complicates SwiftUI’s Unidirectional Data Flow by Introducing Bidirectional Flow</strong></h3><h4><strong>Argument:</strong></h4><p>A common concern with <strong>MVVM</strong> is that it can lead to overly complex layers, such as unnecessary bidirectional updates or performance issues due to excessive refreshes in SwiftUI, complicating state management. Additionally, SwiftUI previews can become difficult to use when views are tightly coupled to their ViewModels, requiring significant effort to bring the ViewModel into the correct state for previewing or mocking.</p><h4><strong>Rebuttal:</strong></h4><p>This argument mischaracterizes <strong>MVVM</strong>. In a well-implemented <strong>MVVM</strong> architecture, the data flow remains unidirectional: the ViewModel processes and transforms data, passing it to the View, while the View sends user interactions back to the ViewModel. This maintains SwiftUI’s declarative nature without introducing complex bidirectional flows.</p><p>Concerns about preview complexity and performance issues often arise from improper implementation rather than inherent flaws in <strong>MVVM</strong>. Software engineers may struggle to correctly separate UI presentation from business logic, leading to “massive” ViewModels or views tightly coupled to logic. However, when implemented properly, <strong>MVVM</strong> improves the separation of concerns and testability without compromising the benefits of SwiftUI previews.</p><p>A well-designed ViewModel should manage only the necessary data and transformations, keeping the view simple and focused on UI rendering. For instance, <a href="https://medium.com/u/b06616cff245">Dave Poirier</a>’s <a href="https://medium.com/swift2go/swiftui-opinion-viewmodel-doesnt-belong-in-previews-62d9e1485b38">blog</a> offers an excellent example of how to decouple the ViewModel from SwiftUI views, enabling simpler, more reusable previews while still benefiting from <strong>MVVM</strong>’s architectural strengths.</p><p>When applied correctly, <strong>MVVM</strong> doesn’t hinder development but rather enhances it. It ensures the right abstraction, preventing views from becoming burdened with business logic while maintaining SwiftUI’s flexibility. The complexity often attributed to <strong>MVVM</strong> stems from misuse, not the pattern itself.</p><p>Here is a basic example of why you can use <strong>MVVM</strong>, and how it helps promote Separation of Concern by decoupling logic from the UI, while also ensuring that your code is scalable, maintainable, and testable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a84f7b232ef1f2b0823cb07d94b2e67/href">https://medium.com/media/5a84f7b232ef1f2b0823cb07d94b2e67/href</a></iframe><p>Injecting the ProductViewModel as an @ObservedObject keeps the view architecture-agnostic, allowing it to focus purely on UI rendering without being coupled to business logic. This also simplifies SwiftUI previews, as mock ViewModels can be easily injected for testing without triggering complex logic.</p><h4>Separation of Concerns:</h4><ul><li>The use of ObservableObject in SwiftUI naturally fits within the <strong>MVVM</strong> pattern, simplifying state management.</li><li>The ProductServiceProtocol protocol enables us to inject dependencies into the ViewModel rather than the view, promoting testability and modularity.</li></ul><h4>Testability:</h4><ul><li>The protocol allows for easy mocking, enabling testing of the ViewModel’s logic without involving the view. This keeps the tests focused and efficient.</li></ul><h4>Business Logic Separation:</h4><ul><li>The fetchProducts()fetchProducts function contains business logic that makes an API request, which should not reside within the view. This reinforces the separation of concerns.</li><li>The filterProducts() function contains additional business logic (e.g., filtering products below a certain price), which should also be decoupled from the view, further supporting the clean separation of responsibilities.</li></ul><h4>Error Management:</h4><ul><li>Errors are managed by the ViewModel, allowing the view to remain solely focused on UI rendering. This approach centralizes error handling, making it more maintainable, while the UI’s responsibility is limited to presenting the error message.</li></ul><h4>Unidirectional Data Flow:</h4><ul><li>The data flow in the ViewModel is unidirectional: it handles data fetching and business logic and then updates the view via @Published properties.</li><li>User actions trigger methods in the ViewModel, maintaining a clear and predictable flow.</li></ul><h3>Conclusion</h3><p>While SwiftUI introduces powerful state management tools and a declarative approach to UI development, it’s essential to remember that <strong>SwiftUI is a framework — not a tool for managing business logic</strong>. Frameworks should not dictate architecture, and this is where design patterns such as <strong>MVVM</strong> come into play, providing a robust structure that should not be overlooked.</p><p><strong>MVVM</strong> ensures a clear separation of concerns, making your codebase more modular, testable, and maintainable. Even with the rise of SwiftUI, the foundational principles of <strong>MVVM</strong> remain invaluable, particularly in large-scale, complex applications. By embracing <strong>MVVM</strong>, software engineers can build scalable and efficient applications while fully leveraging the strengths of SwiftUI. No matter which framework you use, the view should remain as simple as possible, with the core logic placed in a layer where it can be easily tested and maintained — independent of the UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9d26404cf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Considerations When Using SwiftUI]]></title>
            <link>https://medium.com/@77adekunle/performance-considerations-when-using-swiftui-594202bb1d2e?source=rss-3dac943aea19------2</link>
            <guid isPermaLink="false">https://medium.com/p/594202bb1d2e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Ade Adegoke]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 06:51:00 GMT</pubDate>
            <atom:updated>2024-10-15T10:58:45.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FQbd5fyT8hzE1R_P" /><figcaption>Photo by <a href="https://unsplash.com/@mikenewbry?utm_source=medium&amp;utm_medium=referral">Mike Newbry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Performance is paramount when implementing views in SwiftUI. Due to its declarative nature, improper management can lead to inefficiencies. Here’s how to optimize view rendering and reduce body invalidation in SwiftUI. Here’s how to optimize view rendering and body invalidation in SwiftUI.</p><h3><strong>Minimize View Invalidation</strong></h3><p>Each time the state updates, SwiftUI re-renders the body of views. Excessive invalidation can cause performance issues. Efficient use of property wrappers such as <strong>@State</strong>, <strong>@Binding</strong>, <strong>@ObservedObject</strong>, and <strong>@EnvironmentObject</strong> is crucial.</p><p><strong>@State Usage:</strong> Only apply <strong>@State</strong> to properties that change the UI. Applying the @State property wrapper to properties that directly affect the UI triggers unnecessary re-rendering of the view.</p><p><strong>Parent-Child State:</strong> Placing <strong>@State</strong> in a parent view affects performance. For instance, changes in <strong>@State</strong> in the parent trigger re-renders in multiple child views. Move the state to child views to localize changes and reduce unnecessary re-renders.</p><h3>Limit Expensive Modifiers</h3><p>Avoid using multiple Modifiers like <strong>.shadow</strong> , <strong>.blur</strong>, or <strong>.cornerradius</strong>, overusing them can impact performance, especially in large views or animations. For instance, using opacity on an image means SwiftUI renders it at full opacity first, then overlays a transparent layer. Pre-render effects where possible.</p><h3>Lazy Rendering with Lazy Stacks and Grids</h3><p><strong>LazyVStack</strong>, <strong>LazyHStack</strong>, <strong>LazyVGrid</strong>, and <strong>LazyHGrid</strong> are Lazy containers which can help improve performance, especially with large datasets. They render only visible views, enhancing performance, unlike <strong>VStack</strong> or <strong>HStack</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44802abb4b1b12658369cc170cf9e3fb/href">https://medium.com/media/44802abb4b1b12658369cc170cf9e3fb/href</a></iframe><h3>Efficient Data Flow with @Binding and @ObservedObject</h3><p>Use <strong>@Binding</strong>instead of passing full <strong>@State</strong> or <strong>@ObservedObject</strong> instances, to prevent unwanted updates. This keeps data flow efficient and avoids unnecessary re-renders, ensuring your app remains snappy and maintainable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9777d8ac3d3fb98f549d112ed6e2eb78/href">https://medium.com/media/9777d8ac3d3fb98f549d112ed6e2eb78/href</a></iframe><p>The code above demonstrates how to pass data efficiently preventing unnecessary view re-renders, <strong>ItemViewModel</strong> manages a list of items, and the <strong>ContentView</strong>ContentView holds an <strong>@StateObjcet</strong> for the <strong>ItemViewModel</strong>ItemViewModel, A specific item is passed as a <strong>@Binding</strong> instead of the whole <strong>@ObservedObject</strong> instance to the ItemDetailView.</p><h3>Leverage View Redrawing Control with @ViewBuilder</h3><p>Use <strong>@ViewBuilder</strong> to construct views only when needed. This is useful for conditionally creating different views or handling complex view-building logic, as it optimizes the building process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1f9c8c14e01ac9e826d339d7d96c583/href">https://medium.com/media/d1f9c8c14e01ac9e826d339d7d96c583/href</a></iframe><h3>Conclusion</h3><p>By keeping performance in mind while designing an application in SwiftUI, you’ll be making sure that it renders fluidly and efficiently, without any extraneous re-rendering going on, and the user experience is quite buttery smooth. This includes efficient state management, judicious usage of modifiers, leveraging lazy containers in the case of large datasets, and streamlined data flow with <strong>@Binding</strong>. These strategies put together will go a long way in enhancing your application’s performance and responsiveness, consequently enhancing user satisfaction, thereby making your SwiftUI applications truly top-class in both usability and functionality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594202bb1d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Cosmos of Object-Oriented Programming.]]></title>
            <link>https://medium.com/@77adekunle/exploring-the-cosmos-of-object-oriented-programming-4f7771859d3e?source=rss-3dac943aea19------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f7771859d3e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[object-oriented-program]]></category>
            <dc:creator><![CDATA[Ade Adegoke]]></dc:creator>
            <pubDate>Wed, 10 May 2023 08:22:27 GMT</pubDate>
            <atom:updated>2023-05-10T08:22:27.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qlQlTnv2lSWlz_Hl" /><figcaption>Photo by <a href="https://unsplash.com/@jeremythomasphoto?utm_source=medium&amp;utm_medium=referral">Jeremy Thomas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Object-Oriented Programming is often called “a paradigm based on the concept of “objects”, which can contain data and code. Objects are created as instances of classes, encapsulating data and behaviours within them.</p><p>Objects can effectively manage and manipulate their own data without interfering with other objects. This makes organising and maintaining complex systems easier, as each object can operate independently while still interacting with other objects in a controlled manner.</p><p>OOP focuses on Abstraction, Encapsulation, Inheritance, and Polymorphism. In this article, I will explain all four concepts that can be used with the Swift programming language.</p><h4><strong>Abstraction</strong></h4><p>Abstraction is the process of simplifying complex objects. It involves creating abstract classes or interfaces that define a group of objects&#39; common properties and behaviours, without specifying their exact implementation. Abstraction helps to make your code easier to maintain and test. Using modular programming can make your code easier to understand and maintain. It also helps to organize different parts of your code and improve the overall design of your application.</p><p>The code below shows how abstraction can be used with protocols.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/292aa7ec311ccf65e2c3b9e2a04b1c8b/href">https://medium.com/media/292aa7ec311ccf65e2c3b9e2a04b1c8b/href</a></iframe><p>With abstraction, any class like the Car and Motorcycle conform to the Vehicle protocol and can have implementations specific to the individual class requirements.</p><h4><strong>Encapsulation</strong></h4><p>Encapsulation is the concept of concealing detailed implementations contained within an object from the rest of an application. In programming, it is sometimes important to keep some functionality hidden/private/inaccessible, to prevent other objects from altering their main operation. One of the main ways to practice this Encapsulation with Swift is by declaring properties and methods as private. In Swift, you can declare objects internal, this will allow it to be accessible within the same module but prevent other modules from accessing these objects.</p><h4><strong>Inheritance</strong></h4><p>Inheritance in programming is the ability for one object (subclass) to get all the characteristics of another object (superclass), these include properties and methods.</p><p>Inheritance helps your code to be reusable, preventing you from writing duplicated code. In essence, classes in Swift can use functionality from its superclass as if they were implemented inside their own class. Adopting inheritance when writing code can help reduce code complexity, making it simpler, concise, and easier to read, maintain and debug.</p><p>As shown in the code below, inheritance allows the Car class to reuse existing code from its superclass Vehicle .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6e2d349da87ae3f6ad85620061d770f/href">https://medium.com/media/f6e2d349da87ae3f6ad85620061d770f/href</a></iframe><h4><strong>Polymorphism</strong></h4><p>Polymorphism is a Greek word that means “many-shaped”, in programming this means when an object can take many forms. Polymorphism allows different objects to be treated as if they were identical.</p><p>The code below shows how polymorphism is adopted in Swift. The Cat and Dog subclasses inherit from the Animal superclass, also overriding the makeSound() method, for their individual specification. This allows the animal and anotherAnimal instances to operate in the same way but produce different results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3586f7025d8ef741a65792a49264fd38/href">https://medium.com/media/3586f7025d8ef741a65792a49264fd38/href</a></iframe><h4>Overall</h4><p>In addition to what I have mentioned above, OOP helps you create code modularity, making it easier to develop, test, and maintain. Working in a team, OOP allows engineers to work on individual modules without impacting other modules. OOP is suitable for large complete software. There is one drawback to OOP which is the learning process which is more difficult to learn and understand than other programming paradigms, such as Functional Programming, Procedural Programming and Event-Driven Programming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f7771859d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blast Off Your iOS Knowledge with Swift Classes and Structs]]></title>
            <link>https://medium.com/@77adekunle/blast-off-your-ios-knowledge-with-swift-classes-and-structs-7d1467897fca?source=rss-3dac943aea19------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d1467897fca</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[swift-ios-app-development]]></category>
            <dc:creator><![CDATA[Ade Adegoke]]></dc:creator>
            <pubDate>Thu, 04 May 2023 15:20:49 GMT</pubDate>
            <atom:updated>2023-07-06T08:14:50.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZylfME_SxApS6dAL" /><figcaption>Photo by <a href="https://unsplash.com/@spacex?utm_source=medium&amp;utm_medium=referral">SpaceX</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As an iOS software engineer, it is imperative to have a precise understanding of classes and structures, commonly referred to as “structs”. This includes comprehending their similarities, differences, and appropriate usage. Particularly as a junior iOS engineer, one should expect to be evaluated on this topic during the interview process.</p><h4><strong>What are they?</strong></h4><p>Classes and structs are fundamental components of program code, as defined by Apple, the creator of the Swift programming language. Essentially, a class or struct represents a block of code that serves as a template for generating objects within your program. In programming terminology, an object is the product of a class or struct and can be thought of as an instance of that class or struct. While the traditional term for an instance of a class is still in use, the term “instance” is now more commonly applied to both classes and structs, due to the numerous similarities they share with one another, as well as with other programming languages.</p><h4><strong>Similarities</strong></h4><p>Here are some of the similarities that classes and structs share, they can</p><ol><li>Define properties for storing values</li><li>Conform to protocols</li><li>Add initialization for preparing the initial state of objects/instances</li><li>Add methods</li><li>Be extended to add more functionality</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5755d60a9527fd676665166a9da18032/href">https://medium.com/media/5755d60a9527fd676665166a9da18032/href</a></iframe><p><em>A protocol defines a template of methods and properties that must be adopted by any class or structs that conform to it.</em></p><h4>Class differences</h4><p>Classes have the ability to inherit from other classes, allowing for the creation of a subclass that inherits all the characteristics of its superclass. To prevent a class from being inherited, the keyword “final” can be added before declaring the class.</p><p>Additionally, a deinit method can be added to a class, which is the code that is executed when the application wishes to destroy an instance of the class that is no longer needed or in use. The deinit method is executed before the instance is deallocated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4552d0ca6b2df9c025da1a63cfc21be6/href">https://medium.com/media/4552d0ca6b2df9c025da1a63cfc21be6/href</a></iframe><p>Typecasting is another ability that classes possess. Typecasting is not unique to classes, structs can be typecast too. The difference is that structs don’t have superclasses, so structs would usually be typecast from an existential instead of a superclass. This involves checking the type of an instance or treating it differently from its superclass. The identical operator “===”, can be used with classes to determine whether two instances are pointing to the same object.</p><h4>Structs differences</h4><p>In Swift, properties created within a struct are automatically initialized, thereby eliminating the need to explicitly assign values to them. In contrast, classes require all properties to be assigned a value during initialization.</p><p>Structs are immutable. If an instance of a struct is created as a constant, any methods within the struct cannot alter the value of its properties. To modify the value of a constant property, the <strong>mutating</strong> keyword must be added to the method, enabling it to change the value of any variables.</p><h4>Classes are reference types and structs value types</h4><p>In Swift, classes and structs are distinct types, with classes being reference types, and structs being value types.</p><p>Reference types point to the same single copy of data, meaning that if an instance of a class is copied or multiple copies are created, all of the copies reference the original instance. Consequently, any changes made to any of the copies or the original instance will be reflected across all copies.</p><p>On the other hand, value types, such as structs, create a unique copy when an instance is copied. Each copy is distinct and independent, with changes made to one copy not affecting the original instance or any other copies. Therefore, mutations of a value-type instance only affect the copy being modified, leaving the original instance and any other copies unaffected.</p><h4>Memory</h4><p>The Swift programming language employs distinct memory management approaches for classes and structs. When an instance of a struct is created, Swift allocates space in memory specifically for that instance, and when the instance is copied, a new space in memory is allocated for each copy. As a result, each instance and its copies have their own unique memory space, or pointer, in computer programming terms.</p><p>In contrast, when an instance of a class is created, memory space is allocated for that instance, but copies created from the instance refer to the same memory space as the original instance. Essentially, the instance and all its copies reference the same memory address.</p><p>As an iOS software engineer, it is essential to grasp these concepts. In Swift, when instances or copies of structs are no longer used, their memory is destroyed or deallocated.</p><h4>Automatic Reference Counting (ARC)</h4><p>Swift uses Automatic Reference Counting (ARC) to manage a class memory. When an instance of a class is created and memory is allocated, ARC keeps count of every copy of the instance that points to the instance’s memory, until all the copies are no longer in use, or the references count has returned to zero that is when ARC will deallocate the instance’s memory.</p><h4>References Circle</h4><p>There are cases when Swift can not deallocate memory when an instance is no longer in use. One of these cases is when two instances reference each other. When one of the instances is no longer in use and it needs to be deallocated, it cannot because another instance is referred to it, this is also known as a retaining circle. This can cause memory leaks. In order to prevent this one of the references needs to be created as weak or unowned. ARC does not count weak references, so all Instances that have weak references referring to it can be deallocated when it is no longer in use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce20385ae4dc6232171873d90ce78f93/href">https://medium.com/media/ce20385ae4dc6232171873d90ce78f93/href</a></iframe><p><em>In Swift, there are three types of references, weak, unowned and strong. By default all references are strong.</em></p><p>In Swift, references between instances can be established using weak or unowned references. When an instance refers to another instance using a weak reference, the former can only be created as an optional. In addition, if the instance referred to by the weak reference is deallocated, the instance with the weak reference is automatically set to nil.</p><p>Unowned references, on the other hand, are non-optional. This means that you would use an unowned reference if you do not want to create an instance as an optional. However, it is crucial to ensure that the instance referred to by the unowned reference has not been deallocated when it is accessed. If the instance has been deallocated, it can cause the program to crash. Therefore, it is important to be careful when using unowned references in your Swift code.</p><h4>Choosing Classes or Structs</h4><p>When deciding whether to use a class or struct, there are several factors to consider. For example, if you need to create a block of code that needs to inherit from a superclass or if you’re making a base class that will be used to create subclasses, then choose a class. On the other hand, if you’re modelling data, it’s better to choose a struct because it can be passed around within your application by making unique copies that can’t be mutated by other copies. Additionally, structs are thread-safe, making them suitable for use in multithreaded environments.</p><p>Another factor to consider is memory management. Classes are reference types, meaning that when you create an instance of a class, it’s stored in memory, and any other instances that are created from that class refer to the same memory location. This can lead to unexpected behaviour if you’re not careful, especially if you’re dealing with multithreaded environments. On the other hand, structs are value types, which means that each instance has its own unique memory location, and changes to one instance won’t affect other instances.</p><p>Finally, performance can be a factor when deciding between classes and structs. The speed of access is roughly the same, it’s the allocation and deallocation costs that are different. Allocating on the stack is fast because the amount of memory you need to allocate is known by the compiler. Allocating on the heap is slower, because the amount of memory is known only at run-time, and access to the heap needs to be synchronised to be thread-safe, and that has a performance overhead. However, the performance difference may not be significant in many cases, so it’s important to consider other factors as well.</p><h4>Conclusion</h4><p>Because of structs characteristics, Apple has stated that we should choose structs by default, as it is easy for the compiler to reason with it. If you decide that you need to, you can always change a struct into a class.</p><p>However, Classes have the benefit of interloping between Swift and Objective-C and inheriting from other classes. <br> In general, you should choose between classes and structs based on the specific requirements of your code, therefore you need to put apply some thought before you start developing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d1467897fca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>