<?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 Nicolle Policiano on Medium]]></title>
        <description><![CDATA[Stories by Nicolle Policiano on Medium]]></description>
        <link>https://medium.com/@nicolle.fabri?source=rss-eb2394461e8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G8DrAOi3s66HdjhstDsPKg.jpeg</url>
            <title>Stories by Nicolle Policiano on Medium</title>
            <link>https://medium.com/@nicolle.fabri?source=rss-eb2394461e8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 02:32:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolle.fabri/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[Unit Tests: Strategies for Naming, Structuring, and Setup]]></title>
            <link>https://medium.com/policiano/unit-tests-strategies-for-naming-structuring-and-setup-c9dfb5f9bef3?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9dfb5f9bef3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 02:54:45 GMT</pubDate>
            <atom:updated>2024-04-14T19:03:56.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a8f5YHIQDAS-0nN0" /><figcaption>Photo by <a href="https://unsplash.com/@joelfilip?utm_source=medium&amp;utm_medium=referral">Joel Filipe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing effective unit tests in Swift involves some strategies that optimize clarity, maintainability, and execution speed. This article will explore approaches for naming, structuring, and setting up unit tests, using examples from a hypothetical application that fetches movie details.</p><p>Consider the following Swift code examples that demonstrate two unit tests for a <strong>MovieDetailsViewModel</strong>:</p><pre>final class MovieDetailsViewModelTests: XCTestCase {<br>    private func makeSUT(stubbing result: Result&lt;MovieDetails, Error&gt;) -&gt; MovieDetailsViewModel {<br><br>        let service = MovieDetailsServiceSpy()<br>        service.expectedResult = result<br>		    <br>        let sut = MovieDetailsViewModel(service: service)<br>        <br>        return sut<br>    }<br><br>    // Failure to fetch data<br>    func testStateIsErrorWhenFetchingFails() {<br>        // Given<br>        let sut = makeSUT(stubbing: .failure(ErrorDummy()))<br><br>        // When<br>        sut.fetchMovieDetails()<br><br>        // Then<br>        XCTAssertEqual(sut.state, .error)<br>    }<br>    <br>    // Success in fetching data<br>    func testStateIsContentWhenFetchingSucceeds() {<br>        // Given<br>        let expectedMovieDetails = MovieDetails(name: &quot;Some Movie&quot;)<br>        let sut = makeSUT(stubbing: .success(expectedMovieDetails))<br><br>        // When<br>        sut.fetchMovieDetails()<br><br>        // Then<br>        XCTAssertEqual(sut.state, .content(expectedMovieDetails))<br>    }<br>}</pre><h3>Test Naming</h3><p>Effective test naming is crucial for clarity and ease of maintenance. The names should be concise yet descriptive, outlining the test’s scope and expected result, similar to git commit messages. Adopting a consistent naming pattern is beneficial, especially in scenarios with multiple functions, to facilitate reviews.</p><p>In the example above, the first test ensures that an error state is triggered upon a fetch failure, and the second one ensures that a content state is set upon fetch success. Both tests have similar names, starting with the word test followed by a short description in the camel case. Let’s take this one:</p><pre>testStateIsErrorWhenFetchingFails</pre><ul><li>“State is error …”: This is the outcome or the expected result.</li><li>“… when fetching …”: Fetching is the action we are testing.</li><li>“… fails.”: The precondition for the test is that it fails on fetch.</li></ul><p>Naming becomes easier when the test is trivial. In the next section, we will see tips for achieving this triviality.</p><h3>Test Structuring</h3><p>Tests should be compact and run quickly, targeting a single functionality and good readability. The structuring of the test can follow known patterns such as Given/When/Then or Arrange/Act/Assert, which helps organize the test code into three logical parts. Both patterns are similar in their meaning, so:</p><ul><li><strong>Given/Arrange:</strong> Prepares the environment and test variables.</li><li><strong>When/Act:</strong> Invokes the method under test.</li><li><strong>Then/Assert:</strong> Checks the results against expected outcomes.</li></ul><p>Back to the example, you will notice that I partitioned the test into three steps:</p><pre>// Given<br>let sut = makeSUT(stubbing: .failure(ErrorDummy()))<br><br>// When<br>sut.getMovieDetails()<br><br>// Then<br>XCTAssertEqual(sut.state, .error)</pre><p>Commenting on the sections is up to you. The simpler and more compact the tests are, the easier they are to read, so commenting can sometimes become too obvious.</p><h3>Single Assertion</h3><p>During my learning, I was tempted to throw a bunch of assertions into a single test to reuse the test setup. However, figuring out a name for the test becomes more challenging when we have many assertions. What exactly are you testing?</p><p>When possible, it is advisable to stick with a single assertion per test to enhance test clarity and focus. This approach facilitates easier diagnosis when tests fail and ensures that each test addresses a unique aspect of functionality according to the single responsibility principle. For tests requiring multiple validations, consider dividing them into separate tests.</p><pre>// Then<br>XCTAssertEqual(sut.state, .content(expectedMovieDetails))</pre><h3>Test Setup Organization</h3><p>Keeping the test setup organized and separate from the test body is important to avoid code duplication. For example, if several tests require similar configurations, this setup can be moved to a <strong>setUp</strong> method executed before each test. I personally prefer to create a factory method, which I name makeSUT. The factory method approach has a few more advantages, such as tracking for memory leaks and so on. I would like to write a dedicated post for it.</p><p>This not only reduces code duplication but also makes each test easier to read and maintain.</p><pre>private func makeSUT(stubbing result: Result&lt;MovieDetails, Error&gt;) -&gt; MovieDetailsViewModel {<br>    let service = MovieDetailsServiceSpy()<br>    service.expectedResult = result<br>      <br>    let sut = MovieDetailsViewModel(service: service)<br>        <br>    return sut<br>}</pre><h3>Conclusion</h3><p>It has been challenging to learn and adopt unit tests in my workflow, and any convention to simplify it is very welcome.</p><p>In this post, I presented some conventions that I’ve seen around that really made a difference in my learning. Also, having a standardized and strict way to write tests is crucial when dealing with multiple projects or huge codebases.</p><p>I hope this article helped you somehow. See you next time 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9dfb5f9bef3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/unit-tests-strategies-for-naming-structuring-and-setup-c9dfb5f9bef3">Unit Tests: Strategies for Naming, Structuring, and Setup</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactivity in SwiftUI: @ObservedObject and @StateObject for Dynamic UIs]]></title>
            <link>https://medium.com/policiano/reactivity-in-swiftui-observedobject-and-stateobject-for-dynamic-uis-d1230774f667?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1230774f667</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 21:49:17 GMT</pubDate>
            <atom:updated>2024-04-06T14:48:46.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZxfR7syDDGDR-ss_" /><figcaption>Photo by <a href="https://unsplash.com/@fakurian?utm_source=medium&amp;utm_medium=referral">Milad Fakurian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>SwiftUI stands as a reactive framework, and leverages two helpful tools called ObservedObject and StateObject for creating user interfaces that are not only dynamic but inherently responsive to data changes. In this article, we&#39;ll explore what ObservedObject and StateObject are, how they work with the ObservableObject protocol, and how they make our SwiftUI views dynamic and reactive to data changes.</p><h3>Understanding the ObservableObject Protocol</h3><p>In SwiftUI’s reactive framework, is advisable to consider the principle of separation of concerns in order to maintain clean views focused on UI elements. Take a look at the following example that shows a simple view with no separation of concern:</p><pre>struct BookView: View {<br>    @State var title = &quot;&quot;<br>    @State var isRead = false<br>		<br>    private let networking = Networking()<br><br>    var body: some View {<br>        VStack {<br>            Text(title)<br>            Text(isRead ? &quot;Read&quot; : &quot;Not read&quot;)<br>        }<br>        .task {<br>	    do {<br>                let book = try await networking.fetchBook()<br>                title = book.title<br>                isRead = book.isRead<br>            } catch {<br>                // Error handling<br>            }<br>        }<br>    }<br>}<br><br>class Networking {  <br>    func fetchBook() async throws -&gt; Book {<br>        // Define network request<br>    }<br>}</pre><p>The BookView is taking too much responsibility there. Besides presenting the book data, it&#39;s also fetching and processing the data asynchronously. Given the challenges of unit testing SwiftUI views, we had better isolate the data processing somewhere else and make the View leaner.</p><p>Utilizing a view model helps isolate logic and network requests from UI code. A view model typically employs the @Published property wrapper in conjunction with the ObservableObject protocol, allowing SwiftUI views to react to changes in the view model. This mechanism ensures that updates within the view model result in automatic UI refreshes, keeping the user interface in sync with the new data.</p><p>The ObservableObject protocol on a view model acts as a messenger. It requires a@Published property wrapper to notify the views of data changes. The published is updated on the main thread as views observe it, making it possible to integrate view model and subscribed views.</p><p>Let’s take this BookViewModel class as an example:</p><pre>class BookViewModel: ObservableObject {<br>    @Published var title = &quot;&quot;<br>    @Published var isRead = false<br>    <br>    private let networking = Networking()<br><br>    func onAppear() {<br>        Task {<br>            do {<br>                let book = try await networking.fetchBook()<br>                await MainActor.run {<br>                    self.title = book.title<br>                    self.isRead = book.isRead<br>                }<br>            } catch {<br>                // Error handling<br>            }<br>        }<br>    }<br>}</pre><p>This example demonstrates an asynchronous network request through fetchBook(), followed by updating the title and isRead on the main thread. The @Published property wrapper sends updates whenever those published properties change, automatically triggering view updates as new data is fetched. Now that we have moved a bunch of logic to a View Model, we need to connect it with the View.</p><h3>Subscribing to Updates with ObservedObject and StateObject</h3><p>SwiftUI leverages ObservedObject and StateObject property wrappers to connect views to their data sources. These property wrappers enable views to listen for updates from ObservableObject instances, allowing immediate UI updates upon data changes. When the data changes within an ObservableObject, it triggers notifications to views that employ either ObservedObject or StateObject. These views listen for these updates, redrawn, and update themselves to reflect the new state. The refactored view using the view model will look like this:</p><pre>struct BookView: View {<br>    @StateObject var viewModel = BookViewModel()<br><br>    var body: some View {<br>        VStack {<br>            Text(viewModel.title)<br>	    Text(viewModel.isRead ? &quot;Read&quot; : &quot;Not read&quot;)<br>       }<br>       .onAppear {<br>           viewModel.onAppear()<br>       }<br>    }<br>}</pre><p>To effectively manage and present this dynamic data, the SwiftUI View needs to be reactive to changes in the view model. This requires using either ObservedObject or StateObject within the view to observe properties marked with @Published in the view model. This setup ensures that the view automatically reflects updates to its data.</p><p>This is an example using the ObservedObject property wrapper. It looks very similar to the example above.</p><pre>struct BookView: View {<br>    @ObservedObject var viewModel = BookViewModel()<br><br>    // ...<br>}</pre><p>They look very similar in syntax, but what are the effective differences? When do we use each one?</p><h3>StateObject vs ObservedObject</h3><p>Both StateObject and ObservedObject are property wrappers used in SwiftUI to allow a view to observe and respond to changes in a view model&#39;s data. The choice between the two depends on how you want to manage the lifecycle of your data in relation to the view&#39;s re-creation.</p><p><strong>ObservedObject</strong>:</p><ul><li>Ideal for data models that exist outside the view and whose changes need to be monitored by the view. However, careful management is necessary to avoid data resets on view redraws, especially in scenarios where maintaining the state of the data across view updates is required.</li><li>When the parent view redraws, it can re-instantiate all other child views. In this process, any ObservedObject directly created within a view will be recreated, leading to a data reset. Following the natural behavior of object-oriented programming, the view model will also be re-instantiated, resulting in a reset of the data, reverting to the initial presentation of the view model. This can be problematic, as the data returns to its initial state.</li><li>We need to be careful when initializing the ObservedObject directly in the view in order to avoid data loss after the view&#39;s redraw. To use the ObservedObjectsafely, we should inject it into the view, instead of instantiating it directly within the view, ensuring that the object maintains its state after the view&#39;s redraw.</li></ul><p>A classic example is a CounterView that increments count by 1 each time it is tapped, dynamically reacting to changes in a shared Store marked as @ObservedObject.</p><p>The ContentView integrates the CounterView passing store via init to maintain a shared state after the view redraws, and also tracks a local @State redrawCount for additional display demonstrating every redrawn in the view.</p><pre>class Store: ObservableObject {<br>    @Published var count = 0<br>}<br><br>struct CounterView: View {<br>    @ObservedObject var store: Store<br><br>    var body: some View {<br>        Text(&quot;Count: \(store.count)&quot;)<br>            .onTapGesture {<br>                store.count += 1<br>            }<br>    }<br>}<br><br>struct ContentView: View {<br>    @State var redrawCount = 0<br>    @ObservedObject var store = Store()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Taps: \(redrawCount)&quot;)<br>                .onTapGesture {<br>                    redrawCount += 1<br>                }<br>            CounterView(store: store)<br>        }<br>        .padding()<br>    }<br>}</pre><p>The following example demonstrates the Store being initialized directly inside the CounterView, leading to a reset of the count value every time the view redraws. This happens as each view instantiates its own Store as anObservedObject instead of reusing a shared instance.</p><pre>struct CounterView: View {<br>   @ObservedObject var store: Store()<br>    <br>    var body: some View {<br>        Text(&quot;Count: \(store.count)&quot;)<br>            .onTapGesture {<br>                store.count += 1<br>            }<br>    }<br>}<br><br>struct ContentView: View {<br>    @State var redrawCount = 0<br>    @ObservedObject var store = Store()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Taps: \(redrawCount)&quot;)<br>                .onTapGesture {<br>                    redrawCount += 1<br>                }<br>            CounterView()<br>        }<br>        .padding()<br>    }<br>}</pre><p><strong>StateObject</strong>:</p><ul><li>The StateObject is used to store data within the view itself. It is designed to maintain the persistence of the data even when the view is redrawn, unlike the ObservedObject.</li><li>Unlike ObservedObject, a StateObject is not recreated during view redraws. If a parent view is redrawn, SwiftUI maintains the instance of the data model marked with StateObject and reinjects it into the recreated view. This preserves the data model&#39;s state through redraws, avoiding the loss of data changes.</li><li>By using StateObject, you ensure that the state of your data is maintained without the need to manage dependency injection manually, as is recommended with ObservedObject to avoid data resets.</li></ul><p>The following example demonstrates the implementation of the @StateObject property wrapper:</p><pre>struct CounterView: View {<br>    @StateObject var store = Store()<br><br>    var body: some View {<br>        Text(&quot;Count: \(store.count)&quot;)<br>            .onTapGesture {<br>                store.count += 1<br>            }<br>    }<br>}<br><br>struct ContentView: View {<br>    @State var redrawCount = 0<br>    @StateObject var store = Store()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Taps: \(redrawCount)&quot;)<br>                .onTapGesture {<br>                    redrawCount += 1<br>                }<br>            CounterView()<br>        }<br>        .padding()<br>    }<br>}</pre><h3>Conclusion</h3><p>In SwiftUI, ObservedObject and StateObject property wrappers, along with the ObservableObject protocol, play crucial roles in creating dynamic and responsive user interfaces. These tools allow UI components to automatically update in response to data changes. ObservedObject is used for observing external data models and requires careful management to prevent data loss on view redraws. StateObject is used for data that is integral to the view, ensuring data persistence through redraws without the need for manual dependency injection.</p><p>If you want to get more details about this topic, I have a great <a href="https://www.avanderlee.com/swiftui/stateobject-observedobject-differences/">article from SwiftLee</a> that helped me a lot on understanding it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1230774f667" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/reactivity-in-swiftui-observedobject-and-stateobject-for-dynamic-uis-d1230774f667">Reactivity in SwiftUI: @ObservedObject and @StateObject for Dynamic UIs</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View State Management]]></title>
            <link>https://medium.com/policiano/view-state-management-b71813f500a1?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71813f500a1</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 03:23:56 GMT</pubDate>
            <atom:updated>2024-03-28T03:42:08.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>View State Management: Enum vs Properties in SwiftUI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Dhu0Wp89_xC8XHRFMqQRg.png" /></figure><p>In iOS development, efficient application state management is crucial for ensuring dynamic user interfaces and engaging user experiences. The way the view state is managed directly impacts users’ perception of the app’s responsiveness and intuitiveness. In this context, this article explores two different strategies for managing view state: the first one uses different and isolated properties that, together, represent a state of the view, and the second one uses a single enum where each case represents a state of the view.</p><h3>Managing the view state with multiple properties</h3><p>A common approach in SwiftUI involves using multiple properties (usually @State or @Binding) to represent different view states. Consider the example below illustrating this strategy in the context of a book list view.</p><pre>struct BookList: View {<br>    // 1.<br>    @State var isLoading = true<br>    @State var hasError = false<br>    @State var books: [Book] = []<br><br>     var body: some View {<br>        Group {<br>            // 3. <br>            if isLoading {<br>                // Show loading indicator<br>            } else if hasError {<br>                // Show error view<br>            } else {<br>                if books.isEmpty {<br>                    // Show empty list view<br>                } else {<br>                    // Show book list<br>                }<br>            }<br>        }<br>        .task {<br>  	    // 2. <br>            isLoading = true<br>            do {<br>                books = try await getBooks()<br>                hasError = false<br>            } catch {<br>                hasError = true<br>            }<br>            isLoading = false<br>        }<br>    }<br><br>    func getBooks() async throws -&gt; [Book] {<br>        // fetch books asynchronously ...<br>    }<br>}</pre><p>This example can be explained in three parts:</p><ol><li>The main thing that can be noticed in this approach is that there are three different properties that have their own responsibility. The isLoading says whether the view should show the loading indicator or not. The hasError is similar, but it drives to the error view state. Finally, the books is where we store the Book list once it is fetched, kind of representing the success case.</li><li>Right below, at the task modifier, those properties are changed. The steps are straightforward. The View starts loading and fetching the book list. If the list is successfully fetched, the books are stored in the books property. Otherwise, the view will be tagged with an error.</li><li>Eventually, the view will be rendered based on the current values of its properties.</li></ol><p>This approach is straightforward but requires careful management to ensure all possible conditions and potential states are accounted for. For example, this design allows inconsistent states such as:</p><pre>hasError = true<br>isLoading = true<br>books = [Book(...), Book(...), Book(...)]</pre><p>Which state is the view in? Is it loading something? Should it show an error, or should it show the book list? It is not conclusive just by looking at it. This state is not valid.</p><p>Therefore, this design allows for impossible states, as in the example mentioned above. Developers can easily make mistakes and forget to reset the states properly.</p><p>Additionally, the order of the if statements matters when dealing with this strategy.</p><h3>State management with Enums</h3><p>An alternative solution involves encapsulating all possible view states within an enum, which is then managed by a single @State property.</p><pre>enum ViewState {<br>    case content([Book])<br>    case loading<br>    case error<br>}</pre><p>This enum covers the same three possible states presented in the previous approach, and the book list is now integrated as an associated value of the .content case.</p><p>This approach not only simplifies state management but also makes the code more readable and maintainable.</p><p>See the refactored example below:</p><pre>struct BookList: View {<br>    @State var state = ViewState.loading // 1.<br><br>    var body: some View {<br>        Group {<br>	    // 3.<br>            switch state {<br>            case .content(let books) where books.isEmpty:<br>                // Show empty list view<br>            case .content(let books):<br>                // Show book list<br>            case .loading:<br>                // Show loading indicator<br>            case .error:<br>                // Show error view<br>            }<br>        }<br>        .task {<br>	    // 2.<br>            state = .loading<br>            do {<br>                let books = try await getBooks()<br>                state = .content(books)<br>            } catch {<br>                state = .error<br>            }<br>        }<br>    }<br><br>    // ...<br>}</pre><p>Going deeper into the example above, it’s seen the same three steps:</p><ol><li>There is now a single property state that rules them all.</li><li>The state is assigned accordingly. There is no need to reset or toggle properties anymore.</li><li>The view rendering logic is now placed in an easy-to-read switch-case statement.</li></ol><h4>Benefits</h4><p>This strategy offers several benefits:</p><ul><li><strong>Improved Maintainability and Scalability:</strong> Centralizing state management facilitates easier updates and expansions.</li><li><strong>Comprehensive Coverage:</strong> Leveraging Swift’s exhaustive case analysis ensures all possible states are considered, improving code reliability.</li><li><strong>Mutually exclusive states:</strong> Within Swift’s enum, the compiler guarantees that there will be no inconsistent states, so there is no need to reset the properties or manage complex if-else statements.</li></ul><h4>Considerations on this strategy</h4><p>Consider a scenario requiring dynamic navigation titles based on ViewState.</p><pre>.navigationTitle(state == .loading ? &quot;Loading...&quot; : &quot;Book List&quot;)</pre><p>Naturally, the following error may appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LEsGkZD4hInw0HGwPHc8w.png" /><figcaption>Xcode error when trying to compare the state property</figcaption></figure><p>Implementing this approach requires ViewState to conform to Equatable, which means more lines of code because conforming to Equatable is not always trivial, depending on the complexity of the enum&#39;s associated values.</p><p>It can be easily solved by introducing a computed property to the specific state:</p><pre>enum ViewState {<br>    case content([Book])<br>    case loading<br>    case error<br><br>    var isLoading: Bool {<br>        if case .loading = self { true } else { false }<br>    }<br>}</pre><h3>Conclusion</h3><p>In conclusion, using enums to manage app states in SwiftUI makes coding simpler, safer and cleaner. This method puts all the possible states in one place, making it more readable and less likely to miss something. It’s especially good for keeping the code organized and safe from mistakes. However, both the enum way and the multiple @State properties method are useful in Swift. Each has its strengths, so the best choice depends on the needs of the app. I hope this post helps you. See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71813f500a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/view-state-management-b71813f500a1">View State Management</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures vs Async-Await: Asynchronous Operations in iOS]]></title>
            <link>https://medium.com/policiano/closures-vs-async-await-asynchronous-operations-in-ios-b30f78a168f4?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b30f78a168f4</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 19:01:53 GMT</pubDate>
            <atom:updated>2024-03-28T03:30:37.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_cjpkxzlsVdmmmRYRg8rw.png" /></figure><p>Asynchronous programming has always been crucial to developing responsive applications. It allows programs to perform time-consuming tasks, such as network requests or database operations, without freezing the user interface. This article explores two different approaches for managing asynchronous operations in Swift: Closures and Async-Await.</p><h3>Closures</h3><p>Closures in Swift offer a robust mechanism for handling asynchronous operations, enabling the capture of constants and variables from their surrounding context.</p><p>They’re particularly useful as completion handlers for asynchronous operations, allowing you to define the next steps right where the task begins. This approach makes your code easier to maintain by keeping related logic together, especially when dealing with success or failure outcomes of these tasks.</p><h4>Example: Using Closures to handle asynchronous network requests</h4><pre>import Foundation<br><br>class Networking {<br><br>  // Closure-based completion callback function<br><br>  func fetchData(completion: @escaping (Result&lt;Data?, Error&gt;) -&gt; Void) {<br>      let url = URL(string: &quot;https://api.example.com/data&quot;)!<br><br>      let dataTask = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in<br>          guard let self else { return }<br><br>          let result = self.mapToResult(data, error)<br>          completion(result)<br>      }<br><br>      dataTask.resume()<br>  }<br>  <br>  private func mapToResult(_ data: Data?, _ error: Error?) -&gt; Result&lt;Data?, Error&gt; {<br>     if let error = error {<br>         return .failure(error)<br>     } else {<br>         return .success(data)<br>     }<br>  }<br>}<br><br>// Usage<br><br>let networking = Networking()<br><br>networking.fetchData { result in<br>    switch result {<br>    case .success(let data):<br>        print(data) <br>    case .failure(let error):<br>        print(error)<br>    }<br>}</pre><p>This example demonstrates how closures can effectively handle asynchronous callbacks in Swift.</p><p>The <strong>fetchData</strong> function takes a completion closure as a parameter. The <strong>Result&lt;Data?, Error&gt;</strong> neatly wraps the possible outcomes of the fetch operation. The <strong>@escaping</strong> attribute indicates that the closure may be called after the function returns, which is essential for asynchronous calls like network requests.</p><p>The closure is invoked upon the completion of the URLSession’s data task fetching process, leveraging captured context from its surrounding scope (<strong>mapToResult</strong>). This capability to capture and utilize context is useful in integrating the asynchronous operation&#39;s results with the overall application logic.</p><h3>Async-Await</h3><p>The async-await pattern is a modern approach that simplifies working with asynchronous operations. Once it can perform asynchronous operations linearly without nesting, it enhances code readability and maintainability. Moreover, it simplifies error handling, enabling the use of try-catch blocks to manage exceptions.</p><p>In Swift, marking a function with the <strong>async</strong> keyword before its return type indicates that it can perform tasks asynchronously. Within a function, the <strong>await</strong> keyword is used to suspend the function&#39;s execution, waiting for asynchronous tasks to complete without blocking the main thread.</p><h4>Example: Using Async-Await to Fetch Data Asynchronously</h4><pre>import Foundation<br><br>// Asynchronous function definition<br><br>func fetchData() async throws -&gt; Data {<br>    let url = URL(string: &quot;https://api.example.com/data&quot;)!<br>    let (data, _) = try await URLSession.shared.data(from: url)<br>    return data<br>}<br><br>//Usage<br><br>Task {<br>    do {<br>        let data = try await fetchData()<br>        print(data)<br>    } catch {<br>        print(error)<br>    }<br>}</pre><p>In this example, <strong>fetchData</strong> is an asynchronous function marked with <strong>async</strong> that retrieves data from a given URL. The <strong>await</strong> keyword pauses the function&#39;s execution until the network request is completed, allowing other tasks to run concurrently and keeping the app responsive.</p><p>The <strong>Task</strong> runs asynchronous code that can be awaited. This block will not block the main thread while <strong>fetchData</strong> is executing. A do-catch block handles errors thrown by <strong>fetchData</strong>.</p><h3>Closures vs Async-Await</h3><h3>Closures</h3><p><strong>Closures</strong> have been a long-standing method for handling asynchronous tasks in iOS, supported across all iOS versions and widely adopted within the community. They offer the benefits of testability and a robust community knowledge base.</p><p>However, closures come with their set of challenges:</p><ul><li><strong>Memory Leaks and Retain Cycles:</strong> Closures can capture strong references to instances, like <strong>self</strong>, leading to potential memory leaks and retain cycles if not handled cautiously.</li><li><strong>Complex Error Handling:</strong> Asynchronous tasks often involve multiple chained operations, complicating error handling. Closures demand specific error management strategies, especially in nested scenarios, making the code hard to maintain and read.</li><li><strong>Code Readability and Nested Closures</strong>: The deep nesting of closures, or “callback hell,” affects code readability. It stems from layering asynchronous operations within closures, making the code difficult to understand and debug. This emphasizes careful organization and considering alternative patterns to simplify complex nested logic.</li></ul><h3>Async-await</h3><p><strong>Async-await</strong> offers a modern, readable syntax that simplifies writing asynchronous code, making error handling and concurrency management more intuitive. It’s particularly effective at reducing the risk of retain cycles and improving memory management.</p><p>However, its benefits come with certain considerations:</p><ul><li><strong>Limited Availability</strong>: It’s only available on iOS 13 and later, which can limit its use for applications that need to support older versions.</li><li><strong>Memory Management</strong>: Although <strong>async-await</strong> reduces the risk of retain cycles through structured concurrency, memory management still requires careful attention. Capturing <strong>self</strong> weakly in closures for long tasks is essential to prevent memory leaks, as closures remain within <strong>async-await</strong>&#39;s scope.</li><li><strong>Thread Management</strong>: Despite abstracting much of the complexity of managing threads directly, careful attention is needed to ensure UI updates are performed on the main thread.</li><li><strong>Learning curve</strong>: Properly understanding asynchronous programming concepts, including the nuances of async-await, demands time and practice.</li></ul><h3>Conclusion</h3><p>Asynchronous programming is crucial for creating responsive applications in iOS development. The async-await pattern and traditional closures are two distinct approaches to managing asynchronous operations, each with its own advantages and challenges.</p><p>Although async-await represents a significant step forward in simplifying asynchronous code, it requires a deep understanding of its nuances and limitations for effective use. Closures remain indispensable for projects that require backward compatibility or where developers prefer a more traditional approach.</p><p>The choice between the two depends on project’s requirements, target iOS version, and developer familiarity with these methodologies, highlighting that both approaches are valuable and can coexist within the Swift ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b30f78a168f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/closures-vs-async-await-asynchronous-operations-in-ios-b30f78a168f4">Closures vs Async-Await: Asynchronous Operations in iOS</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency and Asynchronous Tasks]]></title>
            <link>https://medium.com/policiano/understanding-concurrency-and-asynchronous-tasks-49f0103c869b?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f0103c869b</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 00:39:43 GMT</pubDate>
            <atom:updated>2024-03-28T03:30:14.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khh95W8XjLs8YL4dwEat1Q.png" /></figure><p>In the programming world, there are two important ideas: concurrency and asynchronous tasks. These concepts serve as a foundation for creating applications that can execute multiple actions simultaneously while staying fast and responsive. In this article, we’ll explain what concurrency means, why the main thread matters, and how asynchronous tasks improve your application’s performance.</p><h3>Concurrency</h3><p>Concurrency refers to the capability of software to perform multiple tasks concurrently, enhancing efficiency and flexibility. Unlike a sequential approach, where tasks are completed one after another, concurrency enables tasks to overlap and run concurrently, though not necessarily executed at the same moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqfK0-MbMv7RyUPvD9mcbA.png" /><figcaption>Sequential tasks in execution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMxk3qdGMchJA1ncSlDiEg.png" /><figcaption>Tasks being executed asynchronously or in parallel</figcaption></figure><h3>Asynchronous Tasks</h3><p>Asynchronous tasks are key to managing tasks that could potentially slow down your application by performing them in the background. This approach allows the application to start a task and move to another without waiting for the first to finish. This prevents the main thread from becoming blocked while waiting for a task to be completed, thereby keeping the application responsive, especially when dealing with waiting operations.</p><p>Examples of asynchronous tasks include:</p><ol><li><strong>Fetching Data from the Internet:</strong> Allows your app to obtain web data without waiting.</li><li><strong>Files or Database Access:</strong> Ensures smooth access to large files or databases without slowdowns.</li><li><strong>Background Process:</strong> Manages downloading large files or running complex calculations in the background, keeping your app functional.</li><li><strong>User Interactions:</strong> Ensures your program can respond to user inputs without delay.</li><li><strong>Heavy Calculations:</strong> Takes care of performing complex math or simulations in the background, preventing your program from freezing.</li></ol><h3>Threading</h3><p>Threading is a crucial concept for understanding concurrency. Threads represent the smallest task execution units that can run independently, allowing complex operations to be broken down into smaller manageable tasks. It enables applications to perform multiple tasks concurrently. For example, while one thread handles user input, another can process data in the background, all without compromising the application’s performance.</p><h3>The Main Thread</h3><p>The main thread also referred to as the UI Thread, acts as the central pillar of the software. It handles the program’s primary tasks and user interactions. However, this thread can slow down when dealing with time-consuming operations, which can affect performance and user experience. To avoid this issue, tasks that are heavy or time-consuming are performed in the background threads. This strategy ensures the application remains quick and responsive.</p><h3>Conclusion</h3><p>In summary, concurrency is a fundamental concept in programming that empowers your applications to run efficiently. It allows your program to multitask with asynchronous tasks, which ensures your program remains responsive, even when dealing with demanding tasks. These concepts are essential in modern programming and enable you to create user-friendly applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f0103c869b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/understanding-concurrency-and-asynchronous-tasks-49f0103c869b">Understanding Concurrency and Asynchronous Tasks</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Git commands every iOS dev should know]]></title>
            <link>https://medium.com/policiano/basic-git-commands-every-ios-dev-should-know-b5a21f027159?source=rss-eb2394461e8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5a21f027159</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Nicolle Policiano]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 19:41:23 GMT</pubDate>
            <atom:updated>2024-03-09T19:07:42.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMSGkeVKFbp5eP8sMS2POw.png" /></figure><p>As an iOS developer, you’re going to need to collaborate with others, maintain different versions of your code, and track your changes over time. Git, a distributed version control system, is an invaluable tool for these tasks. It helps you manage your project’s history, collaborate with your team, and synchronize your local and remote repositories. Here’s a beginner’s guide to some fundamental Git commands that every iOS developer should know.</p><h3>Understanding Repositories</h3><p>First, let’s clarify the two types of repositories:</p><ul><li><strong>Local Repository</strong>: This is stored on your machine and is integrated with your file system. Here, you make changes, commit them, create branches, and perform other local Git operations.</li><li><strong>Remote Repository</strong>: Hosted on a server, like GitHub, this is where your project’s history is preserved. It’s a collaborative space where multiple developers can work on the same project simultaneously.</li></ul><h3>Fundamental Git commands</h3><ul><li>Clone an existing project (git clone)</li><li>Create and switch to a new branch (git checkout -b &lt;new-branch-name&gt;)</li><li>Stage changes (git add)</li><li>Commit changes (git commit)</li><li>Pull updates from the remote repository (git pull)</li><li>Push changes to a remote repository (git push)</li></ul><h3>git clone</h3><p>Use git clone to copy an existing remote repository onto your local machine. It initializes a .git directory, pulls down all the data from the remote repository, and checks out the main branch.</p><h3>git branch</h3><p>Branches allow you to diverge from the main line of development and work independently without affecting the “main” branch. To create a branch, use git branch &lt;branch-name&gt;.</p><h3>git checkout</h3><p>The git checkout command is used to switch between different branches in a Git repository. When you want to work on a new feature or fix a bug, you create or switch to a new branch using this command. It ensures that your changes are kept separate from the main codebase until they are ready to be merged.</p><p><strong>To switch to an existing branch:</strong></p><pre>git checkout &lt;branch-name&gt;</pre><p><strong>To create and switch to a new branch:</strong></p><pre>git checkout -b &lt;new-branch-name&gt;</pre><p>Additionally, if you want to <strong>discard changes in your working directory</strong>, you can use the following command:</p><pre>git checkout -- .</pre><p>This will revert all changes made to files in the current directory to their last committed state, effectively cleaning your working area by removing all non-committed changes.</p><h3>git status</h3><p>This command is your window into the current state of your local repository. It shows what has changed and what’s currently staged for the next commit. This command can produce different outputs, as shown in the examples below.</p><p><strong>Example 1: </strong>Clean working tree</p><pre>On branch main<br> nothing to commit, working tree clean</pre><p><strong>Example 2: </strong>Changes not staged for commit</p><pre>On branch main<br> Changes to be committed:<br> (use &quot;git restore - staged &lt;file&gt;…&quot; to unstage)<br> modified: ContentView.swift</pre><pre>Changes not staged for commit:<br> (use &quot;git add &lt;file&gt;…&quot; to update what will be committed)<br> (use &quot;git restore &lt;file&gt;…&quot; to discard changes in working directory)<br> modified: GitAppExampleApp.swift</pre><h3>git add</h3><p>The git add command is your first step in the staging process, indicating to Git which changes in the working directory should be included for the next commit. This command doesn&#39;t affect the repository until you commit the changes.</p><p>Here’s how you can use it for individual files:</p><pre>git add &lt;file&gt;</pre><p>If you want to stage all the changes you’ve made, including new, modified, and deleted files, you may want to usegit add -A:</p><pre>git add -A</pre><h3>git commit</h3><p>When you’ve staged your changes, you use git commit to actually commit those changes to your local repository’s history. It’s like saving a checkpoint in your project’s development.</p><p>To create a commit with a message, you can use the -m flag followed by your commit message in quotes. This message should be a brief description of the changes you&#39;ve made:</p><pre>git commit -m &quot;Enter a commit message here&quot;</pre><h3>git pull</h3><p>git pull updates your local branch with the latest changes from the remote repository. It’s a combination of git fetch and git merge.</p><p>It is considered best practice to pull the latest updates from the remote repository before starting work and before pushing new commits to keep your local branch up-to-date.</p><h3>git push</h3><p>Finally, git push uploads your local branch commits to the remote repository branch. This shares your changes with the team and integrates them into the main project.</p><h3>Conclusion</h3><p>Mastering these basic Git commands lays the groundwork for efficient and collaborative iOS development. As a passionate beginner iOS developer, this is my very first blog post. My journey into the world of development is just beginning, and I’m excited to share what I learn along the way. I hope this guide serves as a helpful starting point for other beginner developers like myself. Let’s embrace the learning process together and build amazing things. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5a21f027159" width="1" height="1" alt=""><hr><p><a href="https://medium.com/policiano/basic-git-commands-every-ios-dev-should-know-b5a21f027159">Basic Git commands every iOS dev should know</a> was originally published in <a href="https://medium.com/policiano">Policiano</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>