<?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 Diego Perez Salas on Medium]]></title>
        <description><![CDATA[Stories by Diego Perez Salas on Medium]]></description>
        <link>https://medium.com/@diegoperezsalas?source=rss-83e6af1d58e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pRDphqw3g6C-NYGw0_PvbQ.jpeg</url>
            <title>Stories by Diego Perez Salas on Medium</title>
            <link>https://medium.com/@diegoperezsalas?source=rss-83e6af1d58e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:57:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diegoperezsalas/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[Mastering: Unit Testing and UI Testing in the context of iOS development with Xcode]]></title>
            <link>https://diegoperezsalas.medium.com/mastering-both-unit-testing-and-ui-testing-in-the-context-of-ios-development-with-xcode-9b8e74de7d6b?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b8e74de7d6b</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 16:01:49 GMT</pubDate>
            <atom:updated>2024-04-01T16:02:25.668Z</atom:updated>
            <content:encoded><![CDATA[<p>Mastering both Unit Testing and UI Testing in the context of iOS development with Xcode is crucial for ensuring the quality, reliability, and performance of your applications. This comprehensive guide will help you understand the principles, tools, and best practices for effective testing.</p><h3>Unit Testing</h3><p>Unit testing involves testing the smallest parts of your application in isolation (typically individual methods and classes).</p><h4>Principles</h4><ol><li>Isolation: Test components in isolation from the rest of the app.</li><li>Repeatability: Tests should produce the same results every time they’re run.</li><li>Fast Execution: Tests should run quickly to not slow down development or continuous integration processes.</li></ol><h4>Tools and Frameworks</h4><ul><li>XCTest Framework: Apple’s testing framework that integrates seamlessly with Xcode for both unit and UI testing.</li><li>Swift Testing Libraries: Libraries such as Quick and Nimble offer more expressive syntax for writing tests.</li></ul><h4>Best Practices</h4><ol><li>Test Early and Often: Integrate testing into your daily development workflow.</li><li>Use Test Doubles: Utilize mocks, stubs, and fakes to simulate dependencies and isolate the component being tested.</li><li>Achieve High Code Coverage: Strive for high test coverage but prioritize critical paths and functionality.</li></ol><h3>UI Testing</h3><p>UI Testing checks the application’s graphical interface to ensure it functions correctly in response to user actions.</p><h4>Principles</h4><ol><li>User Flow Testing: Focus on testing complete paths through the application’s UI.</li><li>Accessibility: Use accessibility identifiers to reliably interact with UI elements.</li><li>Automate User Interactions: Simulate real user interactions, such as tapping buttons, swiping, and entering text.</li></ol><h4>Tools and Frameworks</h4><ul><li>XCUITest Framework: Part of XCTest, designed specifically for UI testing by simulating user interactions.</li><li>Third-Party Tools: Tools like Appium or Detox for cross-platform UI testing.</li></ul><h4>Best Practices</h4><ol><li>Test Realistic User Scenarios: Reflect real-world use cases.</li><li>Maintainable Test Code: Keep your tests readable and maintainable. Regularly review and refactor them.</li><li>Use Page Object Model: Abstract UI elements and interactions into page objects to reduce code duplication and improve maintainability.</li></ol><h3>Example: Testing a Login View</h3><p>Let’s consider you have a login screen in your app. Here’s how you might approach unit and UI testing for this feature.</p><h4>Unit Test Example</h4><pre>import XCTest<br>@testable import YourApp<br><br>class LoginViewModelTests: XCTestCase {<br>    var viewModel: LoginViewModel!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        viewModel = LoginViewModel()<br>    }<br>    <br>    func testLoginSuccess() {<br>        // Mock networking layer to return success<br>        viewModel.login(username: &quot;test&quot;, password: &quot;password&quot;) { success in<br>            XCTAssertTrue(success)<br>        }<br>    }<br>}</pre><h4>UI Test Example</h4><pre>import XCTest<br><br>class LoginUITests: XCTestCase {<br>    <br>    override func setUp() {<br>        continueAfterFailure = false<br>        let app = XCUIApplication()<br>        app.launch()<br>    }<br>    <br>    func testLoginFlow() {<br>        let app = XCUIApplication()<br>        <br>        let usernameTextField = app.textFields[&quot;Username&quot;]<br>        XCTAssertTrue(usernameTextField.exists)<br>        usernameTextField.tap()<br>        usernameTextField.typeText(&quot;test&quot;)<br>        <br>        let passwordSecureTextField = app.secureTextFields[&quot;Password&quot;]<br>        XCTAssertTrue(passwordSecureTextField.exists)<br>        passwordSecureTextField.tap()<br>        passwordSecureTextField.typeText(&quot;password&quot;)<br>        <br>        app.buttons[&quot;Login&quot;].tap()<br>        <br>        // Add assertion to verify success<br>    }<br>}</pre><p>Mastering unit and UI testing in iOS development with Xcode is essential for building robust and reliable apps. By following the best practices outlined above and making testing an integral part of your development process, you can significantly improve the quality and user experience of your apps. Remember, a well-tested app is a foundation for a great app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b8e74de7d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SwiftUI: HTTP POST request]]></title>
            <link>https://diegoperezsalas.medium.com/mastering-swiftui-http-post-request-267bf94bbd91?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/267bf94bbd91</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 15:46:12 GMT</pubDate>
            <atom:updated>2024-04-01T15:49:48.513Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial will guide you through creating a simple form, capturing user input, and using URLSession to perform a network request to a mock server endpoint.</p><h3>Step 1: Define the Data Model</h3><p>For this example, let’s assume we’re submitting a simple user feedback form with two fields: name and feedback.</p><pre>struct Feedback: Codable {<br>    var name: String<br>    var feedback: String<br>}</pre><h3>Step 2: Create the Form View</h3><p>Next, we’ll build a SwiftUI view that contains a form where users can enter their name and feedback.</p><pre>import SwiftUI<br><br>struct FeedbackFormView: View {<br>    @State private var name = &quot;&quot;<br>    @State private var feedback = &quot;&quot;<br>    @State private var showAlert = false<br>    @State private var alertMessage = &quot;&quot;<br><br>    var body: some View {<br>        NavigationView {<br>            Form {<br>                Section(header: Text(&quot;Your Details&quot;)) {<br>                    TextField(&quot;Name&quot;, text: $name)<br>                    TextField(&quot;Feedback&quot;, text: $feedback)<br>                }<br>                <br>                Button(&quot;Submit&quot;) {<br>                    submitFeedback()<br>                }<br>            }<br>            .navigationTitle(&quot;Feedback&quot;)<br>            .alert(isPresented: $showAlert) {<br>                Alert(title: Text(&quot;Feedback&quot;), message: Text(alertMessage), dismissButton: .default(Text(&quot;OK&quot;)))<br>            }<br>        }<br>    }<br><br>    func submitFeedback() {<br>        guard !name.isEmpty, !feedback.isEmpty else {<br>            alertMessage = &quot;Please fill in all fields&quot;<br>            showAlert = true<br>            return<br>        }<br>        <br>        let feedbackData = Feedback(name: name, feedback: feedback)<br>        postFeedback(feedback: feedbackData)<br>    }<br>}</pre><h3>Step 3: Implement the Networking Logic</h3><p>Now, let’s add the function to perform the HTTP POST request using URLSession. For demonstration purposes, we&#39;ll use a mock server URL like https://jsonplaceholder.typicode.com/posts, which is a free service that simulates data operations.</p><pre>extension FeedbackFormView {<br>    func postFeedback(feedback: Feedback) {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<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>        do {<br>            let jsonData = try JSONEncoder().encode(feedback)<br>            request.httpBody = jsonData<br>            <br>            URLSession.shared.dataTask(with: request) { data, response, error in<br>                if let error = error {<br>                    DispatchQueue.main.async {<br>                        self.alertMessage = &quot;Failed to send feedback: \(error.localizedDescription)&quot;<br>                        self.showAlert = true<br>                    }<br>                    return<br>                }<br>                <br>                guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 201 else {<br>                    DispatchQueue.main.async {<br>                        self.alertMessage = &quot;Failed with status code: \((response as? HTTPURLResponse)?.statusCode ?? -1)&quot;<br>                        self.showAlert = true<br>                    }<br>                    return<br>                }<br>                <br>                DispatchQueue.main.async {<br>                    self.alertMessage = &quot;Feedback sent successfully!&quot;<br>                    self.showAlert = true<br>                }<br>            }.resume()<br>        } catch {<br>            DispatchQueue.main.async {<br>                self.alertMessage = &quot;Failed to encode feedback&quot;<br>                self.showAlert = true<br>            }<br>        }<br>    }<br>}</pre><h3>Step 4: The App Entry Point</h3><p>Finally, ensure your FeedbackFormView is set as the main view in your SwiftUI app&#39;s entry point.</p><pre>@main<br>struct YourApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            FeedbackFormView()<br>        }<br>    }<br>}</pre><h3>Running Your App</h3><p>When you run this app, you’ll have a simple form for submitting feedback. Upon tapping “Submit,” the app collects the input data, encodes it into JSON, and sends it to the server using an HTTP POST request. Errors and success are handled gracefully, displaying alerts to the user.</p><p>This example covers essential aspects of working with forms in SwiftUI, including capturing user input, performing validation, and networking. To extend this further, you might consider implementing more complex validation logic, handling more detailed server responses, or enhancing the user interface.</p><p>Organizing files in an Xcode project is crucial for maintaining readability, manageability, and scalability, especially as the project grows. For the examples we’ve discussed, including forms and fetching data from a network, a logical and structured approach to file organization can significantly help. Here’s a suggested structure that you might find useful:</p><h3>Suggested File Structure for SwiftUI Projects</h3><h3><strong>Model</strong></h3><p>Contains the data models of your application. For network requests and forms, this includes any structs or classes that represent the data you are working with or fetching.</p><p>Example: Feedback.swift for the feedback form data model.</p><h3><strong>View</strong></h3><p>Holds all the SwiftUI view files. If you have a complex UI with many components, you might further organize this folder into subfolders like Components, Screens, or Views.</p><p>Examples:</p><ul><li>ContentView.swift for the main view of your app.</li><li>FeedbackFormView.swift for the feedback form view.</li><li>PostsView.swift for displaying fetched posts.</li></ul><h3><strong>ViewModel</strong></h3><p>Contains the view model files that manage the state and logic for your views. This is where you’d include classes or structs that fetch data from the network, handle form submissions, and prepare data for presentation.</p><p>Examples:</p><ul><li>PostsViewModel.swift for fetching and managing posts data.</li><li>FeedbackViewModel.swift for managing the feedback submission logic.</li></ul><h3>Network</h3><p>Dedicated to networking tasks, including API calls, network request configurations, and any utilities related to networking.</p><p>Examples:</p><ul><li>NetworkingManager.swift for a reusable network manager.</li><li>APIEndpoints.swift could define your app&#39;s API endpoints in a structured way.</li></ul><h3>Utility</h3><p>For general-purpose utilities and helpers that are used across the app. This might include extensions, formatters, and any other utility functions or constants.</p><p>Examples:</p><ul><li>Extensions.swift for common Swift or SwiftUI extensions.</li><li>Constants.swift for defining app-wide constants, like API base URLs.</li></ul><h3>Resources</h3><p>Contains assets, such as images and data files, and other resources like storyboards (if used alongside SwiftUI), localization strings files, and configuration plist files.</p><h3>AppDelegate and SceneDelegate</h3><p>If you’re using them for app lifecycle management, notifications, and other app-wide tasks. With SwiftUI, you might not need to touch these much, but they’re still part of the project structure.</p><h3>Tips for Maintaining the Structure</h3><ul><li>Use Groups: Xcode uses groups (virtual folders) to organize files in the project navigator. Ensure that your file system structure mirrors your group structure for consistency.</li><li>Naming Conventions: Adopt consistent naming conventions for your files and groups, making it easier to locate and understand their purpose.</li><li>Refactoring: As your project evolves, don’t hesitate to refactor your file organization. This might include splitting large files, reorganizing groups, or renaming files for clarity.</li></ul><p>This structure is a starting point and should be adapted based on your project’s specific needs and complexity. The key is maintaining a logical organization that aligns with the architecture of your app, making it easy for any developer to navigate and understand your codebase.</p><p>Creating a full example with navigation, login, registration, feedback form, animations, and subscription management involves a lot of components and is quite comprehensive for a single response. However, I can outline a project structure for you and provide examples for each key part, which you can then expand into a full application.</p><h3>Project Structure Overview</h3><p>Here’s a proposed structure for your Xcode project:</p><pre>YourApp/<br>├── Model/<br>│   ├── UserModel.swift<br>│   └── SubscriptionModel.swift<br>├── View/<br>│   ├── MainView.swift<br>│   ├── LoginView.swift<br>│   ├── RegistrationView.swift<br>│   ├── FeedbackFormView.swift<br>│   └── SubscriptionView.swift<br>├── ViewModel/<br>│   ├── AuthViewModel.swift<br>│   └── SubscriptionViewModel.swift<br>├── Network/<br>│   ├── NetworkManager.swift<br>│   └── APIEndpoints.swift<br>├── Utility/<br>│   ├── Extensions.swift<br>│   └── Constants.swift<br>└── Resources/<br>    ├── Assets.xcassets<br>    └── Info.plist</pre><h3>Model</h3><ul><li>UserModel.swift: Defines the user structure.</li><li>SubscriptionModel.swift: Defines subscription details.</li></ul><h3>View</h3><ul><li>MainView.swift: The root view that manages navigation and displays the main interface.</li><li>LoginView.swift: Presents login fields and connects to AuthViewModel for authentication.</li><li>RegistrationView.swift: Collects new user information and registers them via AuthViewModel.</li><li>FeedbackFormView.swift: Allows users to submit feedback, showing how to use forms.</li><li>SubscriptionView.swift: Displays available subscriptions and handles purchases.</li></ul><h3>ViewModel</h3><ul><li>AuthViewModel.swift: Manages authentication tasks (login and registration).</li><li>SubscriptionViewModel.swift: Handles fetching subscription options and managing purchases.</li></ul><h3>Network</h3><ul><li>NetworkManager.swift: Centralized network requests management.</li><li>APIEndpoints.swift: Defines API endpoints used throughout the app.</li></ul><h3>Utility</h3><ul><li>Extensions.swift: Swift and SwiftUI extensions for reusability.</li><li>Constants.swift: Stores constants, like API base URLs.</li></ul><h3>Example Components</h3><p>Let’s define some components from the structure:</p><h4>NetworkManager.swift</h4><pre>import Foundation<br><br>class NetworkManager {<br>    static let shared = NetworkManager()<br>    <br>    func login(with credentials: Credentials, completion: @escaping (Bool) -&gt; Void) {<br>        // Perform login network request<br>    }<br>    <br>    func fetchSubscriptions(completion: @escaping ([SubscriptionModel]) -&gt; Void) {<br>        // Fetch subscription options<br>    }<br>}</pre><h4>LoginView.swift</h4><pre>import SwiftUI<br><br>struct LoginView: View {<br>    @State private var username: String = &quot;&quot;<br>    @State private var password: String = &quot;&quot;<br>    <br>    var body: some View {<br>        Form {<br>            TextField(&quot;Username&quot;, text: $username)<br>            SecureField(&quot;Password&quot;, text: $password)<br>            Button(&quot;Log In&quot;) {<br>                // Call ViewModel to handle login<br>            }<br>        }<br>    }<br>}</pre><h4>MainView.swift</h4><pre>import SwiftUI<br><br>struct MainView: View {<br>    var body: some View {<br>        TabView {<br>            LoginView()<br>                .tabItem {<br>                    Label(&quot;Login&quot;, systemImage: &quot;person.fill&quot;)<br>                }<br>            RegistrationView()<br>                .tabItem {<br>                    Label(&quot;Register&quot;, systemImage: &quot;person.badge.plus&quot;)<br>                }<br>            FeedbackFormView()<br>                .tabItem {<br>                    Label(&quot;Feedback&quot;, systemImage: &quot;bubble.left.fill&quot;)<br>                }<br>            SubscriptionView()<br>                .tabItem {<br>                    Label(&quot;Subscribe&quot;, systemImage: &quot;star.fill&quot;)<br>                }<br>        }<br>    }<br>}</pre><h3>Implementing Animations</h3><p>Animations in SwiftUI can be easily added with modifiers. For example, in your FeedbackFormView, you might want to animate the submission button to confirm the user&#39;s action:</p><pre>Button(&quot;Submit&quot;) {<br>    // Trigger the animation<br>}<br>.scaleEffect(isAnimating ? 1.2 : 1)<br>.animation(.easeInOut, value: isAnimating)</pre><h3>Managing Subscriptions</h3><p>Handling subscriptions and tokens involves securely communicating with your backend and possibly integrating with StoreKit for in-app purchases. The SubscriptionViewModel would handle fetching available subscriptions and processing purchases, coordinating with NetworkManager for server-side verification.</p><p>This outline and examples give you a foundation to build a comprehensive SwiftUI app featuring authentication, feedback submission, animations, and subscription management. Remember, the key to managing complex projects is keeping your codebase organized and modular. Each component should have a clear responsibility, and you should aim for reusable and maintainable code patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=267bf94bbd91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Fetching Data in SwiftUI for Advanced Developers]]></title>
            <link>https://diegoperezsalas.medium.com/mastering-fetching-data-in-swiftui-for-advanced-developers-4365f892e89a?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4365f892e89a</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 15:10:59 GMT</pubDate>
            <atom:updated>2024-04-01T15:10:59.652Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s app development landscape, fetching data from the internet and seamlessly integrating it into your UI is a fundamental skill. SwiftUI, Apple’s modern framework for building user interfaces, offers a streamlined approach to this task, coupled with Swift’s powerful networking capabilities. This article delves into advanced strategies for fetching and displaying data in a SwiftUI app, ensuring developers can handle complex data models, asynchronous operations, and state management like pros.</p><h4>Foundations of Data Fetching in SwiftUI</h4><p>Before diving into advanced techniques, it’s crucial to understand the basics of fetching data in a SwiftUI application:</p><ul><li>URLSession: Swift’s native API for networking tasks, allowing you to perform HTTP requests, handle responses, and manage sessions.</li><li>Decodable Protocol: Facilitates easy decoding of JSON into Swift data models.</li><li>@Published and ObservableObject: Enable data to be observed by SwiftUI views, allowing for automatic UI updates when data changes.</li></ul><h4>Advanced Data Fetching Techniques</h4><ol><li>Modular Networking Layer: Create a dedicated networking layer that abstracts away the details of making HTTP requests and parsing responses. Use generics and protocols to make it reusable and adaptable to different data models.</li><li>Combine Framework: Leverage the Combine framework for handling asynchronous data fetching and updates. Combine integrates seamlessly with SwiftUI, providing publishers that can be used to update the UI reactively.</li><li>Error Handling and Loading States: Implement comprehensive error handling within your networking layer. Use SwiftUI views to reflect loading states and errors, improving the user experience.</li><li>Caching Mechanisms: Implement caching to reduce network requests and provide faster access to previously fetched data. Consider using URLCache or creating a custom caching solution tailored to your app’s needs.</li></ol><h4>Implementing Advanced Data Fetching</h4><p>Here’s how to implement an advanced data fetching mechanism using Combine and SwiftUI:</p><p>Step 1: Define Your Data Model</p><p>Ensure your data model conforms to the Decodable protocol for easy parsing.</p><pre>struct Post: Decodable, Identifiable {<br>    let id: Int<br>    let title: String<br>    let body: String<br>}</pre><p>Step 2: Create a Networking Manager</p><p>Develop a networking manager that uses generics for fetching and decoding data. Integrate Combine to publish data updates.</p><pre>import Combine<br><br>class NetworkingManager {<br>    func fetchData&lt;T: Decodable&gt;(url: URL) -&gt; AnyPublisher&lt;T, Error&gt; {<br>        return URLSession.shared.dataTaskPublisher(for: url)<br>            .map(\.data)<br>            .decode(type: T.self, decoder: JSONDecoder())<br>            .receive(on: DispatchQueue.main)<br>            .eraseToAnyPublisher()<br>    }<br>}</pre><p>Step 3: ViewModel Using Combine</p><p>Create a ViewModel that subscribes to the networking manager’s publisher, updating the app’s state accordingly.</p><pre>class PostsViewModel: ObservableObject {<br>    var cancellables = Set&lt;AnyCancellable&gt;()<br>    @Published var posts: [Post] = []<br>    @Published var isLoading = false<br>    @Published var error: Error?<br><br>    private let networkingManager = NetworkingManager()<br><br>    func loadPosts() {<br>        isLoading = true<br>        networkingManager.fetchData(url: URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!)<br>            .sink(receiveCompletion: { [weak self] completion in<br>                self?.isLoading = false<br>                if case let .failure(err) = completion {<br>                    self?.error = err<br>                }<br>            }, receiveValue: { [weak self] (posts: [Post]) in<br>                self?.posts = posts<br>            })<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><p>Step 4: SwiftUI View</p><p>Finally, create a SwiftUI view that observes the ViewModel, displaying the data or any error/loading state.</p><pre>struct PostsView: View {<br>    @StateObject var viewModel = PostsViewModel()<br><br>    var body: some View {<br>        NavigationView {<br>            List(viewModel.posts) { post in<br>                Text(post.title)<br>            }<br>            .navigationTitle(&quot;Posts&quot;)<br>            .onAppear { viewModel.loadPosts() }<br>            <br>            if viewModel.isLoading {<br>                ProgressView(&quot;Loading...&quot;)<br>            }<br>        }<br>        .alert(item: $viewModel.error) { error in<br>            Alert(title: Text(&quot;Error&quot;), message: Text(error.localizedDescription), dismissButton: .default(Text(&quot;OK&quot;)))<br>        }<br>    }<br>}</pre><p>Mastering data fetching in SwiftUI involves more than just making network requests; it encompasses managing asynchronous data flow, handling errors gracefully, and ensuring your UI remains responsive and up-to-date. By leveraging Swift’s powerful networking APIs alongside SwiftUI’s reactive UI framework, you can create robust, efficient, and user-friendly data fetching mechanisms. This advanced approach not only enhances code reusability and maintainability but also provides a seamless experience for users, even in the face of complex data handling requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4365f892e89a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Animations in SwiftUI: Creating Smooth and Engaging Interactions]]></title>
            <link>https://diegoperezsalas.medium.com/mastering-animations-in-swiftui-creating-smooth-and-engaging-interactions-eea741869628?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea741869628</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 15:04:08 GMT</pubDate>
            <atom:updated>2024-04-01T15:04:08.908Z</atom:updated>
            <content:encoded><![CDATA[<p>SwiftUI, Apple’s declarative UI toolkit, simplifies the process of building beautiful and interactive user interfaces for all Apple platforms. One of the strengths of SwiftUI is its powerful and easy-to-use animation system. With just a few lines of code, you can add animations that make your app feel more dynamic and engaging. This article will explore advanced concepts in SwiftUI animations, guiding you through creating complex and visually appealing animations.</p><h4>Understanding the Basics</h4><p>Before diving into advanced animations, it’s essential to grasp the fundamental principles of animation in SwiftUI. SwiftUI animations are declarative; you describe the result, and SwiftUI figures out how to get there. To animate changes in your view, you can use the .animation() modifier on views or the withAnimation function for state changes.</p><h4>Customizing Animations</h4><p>SwiftUI provides a range of built-in animations, such as linear, ease-in, ease-out, and spring animations, which can be customized with duration, delay, and damping parameters. For instance, a spring animation can be applied to a view like this:</p><pre>Text(&quot;Hello, SwiftUI!&quot;)<br>    .scaleEffect(isScaled ? 2 : 1)<br>    .animation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 0), value: isScaled)</pre><h4>Creating Complex Animations with Animation Sequences</h4><p>To create more complex animations, you can chain animations together using delays or by triggering animations in sequence based on state changes. Animation sequences allow for the creation of intricate animations that can make your UI stand out.</p><h4>Example: Building a Complex Animation Sequence</h4><p>Let’s create an animation sequence that scales, fades, and rotates a view in sequence:</p><pre>struct ContentView: View {<br>    @State private var isAnimating = false<br><br>    var body: some View {<br>        VStack {<br>            Button(&quot;Animate&quot;) {<br>                isAnimating.toggle()<br>            }<br><br>            Circle()<br>                .frame(width: 100, height: 100)<br>                .foregroundColor(.blue)<br>                .scaleEffect(isAnimating ? 1.5 : 1)<br>                .opacity(isAnimating ? 0.5 : 1)<br>                .rotationEffect(.degrees(isAnimating ? 360 : 0))<br>                .animation(.easeInOut(duration: 1), value: isAnimating)<br>                .animation(.easeOut(duration: 1).delay(0.5), value: isAnimating)<br>                .animation(.linear(duration: 1).delay(1), value: isAnimating)<br>        }<br>    }<br>}</pre><h4>Gesture-Driven Animations</h4><p>SwiftUI also allows for gesture-driven animations, where the animation is controlled by user input, such as drag gestures. This can add an interactive element to your animations, making your app feel more responsive.</p><h4>Implementing a Gesture-Driven Animation</h4><pre>struct DraggableCircleView: View {<br>    @GestureState private var dragOffset = CGSize.zero<br><br>    var body: some View {<br>        Circle()<br>            .frame(width: 100, height: 100)<br>            .foregroundColor(.green)<br>            .offset(dragOffset)<br>            .gesture(<br>                DragGesture()<br>                    .updating($dragOffset, body: { (value, state, transaction) in<br>                        state = value.translation<br>                    })<br>            )<br>            .animation(.spring(), value: dragOffset)<br>    }<br>}</pre><h4>Animating Custom View Transitions</h4><p>Custom view transitions allow for the animation of views when they are inserted or removed from the view hierarchy. By defining custom transitions, you can control how views enter or exit the screen.</p><h4>Creating a Custom Transition</h4><pre>extension AnyTransition {<br>    static var slideAndFade: AnyTransition {<br>        let insertion = AnyTransition.move(edge: .trailing)<br>                        .combined(with: .opacity)<br>        let removal = AnyTransition.scale<br>                        .combined(with: .opacity)<br>        return .asymmetric(insertion: insertion, removal: removal)<br>    }<br>}</pre><p>You can then use this custom transition in your views:</p><pre>MyView()<br>    .transition(.slideAndFade)</pre><p>SwiftUI’s animation capabilities are both powerful and easy to use, providing a wealth of opportunities to enhance your app’s user experience. By understanding and applying these advanced animation techniques, you can create complex, beautiful, and interactive animations that bring your app to life. Experimenting with different animation combinations and timings is key to discovering what works best for your specific use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea741869628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetching Data: Learn how to fetch data from the internet and display it in your SwiftUI app.]]></title>
            <link>https://diegoperezsalas.medium.com/fetching-data-learn-how-to-fetch-data-from-the-internet-and-display-it-in-your-swiftui-app-3d2ff12af9d1?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2ff12af9d1</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Mon, 01 Apr 2024 14:23:28 GMT</pubDate>
            <atom:updated>2024-04-01T14:34:18.697Z</atom:updated>
            <content:encoded><![CDATA[<p>This article will guide you through the process, from making the network request to displaying the fetched data in your SwiftUI app.</p><h3>Introduction to Fetching Data in SwiftUI</h3><p>SwiftUI itself focuses on UI development and doesn’t directly provide networking capabilities. Instead, you use Swift’s URLSession for networking, alongside SwiftUI for displaying the data. Here&#39;s a step-by-step guide to fetching and displaying data from the internet in a SwiftUI app.</p><h3>Step 1: Define Your Data Model</h3><p>First, define a model that represents the data you’re fetching. It should conform to Decodable to easily decode from JSON.</p><pre>struct Post: Decodable, Identifiable {<br>    var userId: Int<br>    var id: Int<br>    var title: String<br>    var body: String<br>}</pre><h3>Step 2: Create a ViewModel to Fetch Data</h3><p>Create a ViewModel that fetches the data and publishes it for your views to display. Use @Published properties to automatically update your views when new data arrives.</p><pre>import Foundation<br>import Combine<br><br>class PostsViewModel: ObservableObject {<br>    @Published var posts: [Post] = []<br><br>    func fetchPosts() {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        <br>        URLSession.shared.dataTask(with: url) { data, response, error in<br>            guard let data = data, error == nil else { return }<br>            <br>            let posts = try? JSONDecoder().decode([Post].self, from: data)<br>            <br>            DispatchQueue.main.async {<br>                self.posts = posts ?? []<br>            }<br>        }.resume()<br>    }<br>}</pre><h3>Step 3: Create a SwiftUI View to Display the Data</h3><p>Now, create a SwiftUI view that uses your ViewModel to display the fetched data.</p><pre>struct PostsView: View {<br>    @StateObject private var viewModel = PostsViewModel()<br><br>    var body: some View {<br>        List(viewModel.posts) { post in<br>            VStack(alignment: .leading) {<br>                Text(post.title)<br>                    .font(.headline)<br>                Text(post.body)<br>                    .font(.body)<br>            }<br>        }<br>        .onAppear {<br>            viewModel.fetchPosts()<br>        }<br>    }<br>}</pre><h3>Step 4: Testing Your App</h3><p>Run your app to see the list of posts fetched from the internet and displayed in your UI. Ensure your app has internet access and the correct permissions to make network requests.</p><p>Fetching data from the internet in a SwiftUI app involves using URLSession to perform the network request, decoding the JSON into Swift models, and using @ObservableObject to bind the data to your UI. This pattern not only keeps your code clean and maintainable but also leverages SwiftUI&#39;s powerful data-driven UI updates. Remember to handle errors and loading states to provide a smooth user experience.</p><h3><strong>Error handling and user notification</strong></h3><p>Handling errors gracefully and notifying the user when something goes wrong is an important part of app development. Let’s modify our previous example to include error handling and user notification.</p><p>We’ll update the PostsViewModel to handle errors by showing an alert to the user when the fetch operation fails.</p><h3>Step 1: Update the ViewModel</h3><p>First, we’ll add an error property to the PostsViewModel to track when an error occurs. We&#39;ll also modify the fetchPosts function to update this property if an error is encountered during the network request.</p><pre>class PostsViewModel: ObservableObject {<br>    @Published var posts: [Post] = []<br>    @Published var showAlert = false // To trigger an alert<br>    @Published var errorMessage = &quot;&quot; // To store the error message<br><br>    func fetchPosts() {<br>        guard let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;) else { return }<br>        <br>        URLSession.shared.dataTask(with: url) { [weak self] data, _, error in<br>            DispatchQueue.main.async {<br>                if let error = error {<br>                    self?.errorMessage = error.localizedDescription<br>                    self?.showAlert = true<br>                    return<br>                }<br>                <br>                guard let data = data else {<br>                    self?.errorMessage = &quot;Data is nil.&quot;<br>                    self?.showAlert = true<br>                    return<br>                }<br>                <br>                do {<br>                    let posts = try JSONDecoder().decode([Post].self, from: data)<br>                    self?.posts = posts<br>                } catch {<br>                    self?.errorMessage = error.localizedDescription<br>                    self?.showAlert = true<br>                }<br>            }<br>        }.resume()<br>    }<br>}</pre><h3>Step 2: Update the ContentView</h3><p>Next, we’ll modify the ContentView to show an alert when showAlert is true. We use the .alert modifier to present an alert dialog with the error message.</p><pre>struct ContentView: View {<br>    @StateObject private var viewModel = PostsViewModel()<br><br>    var body: some View {<br>        NavigationView {<br>            List(viewModel.posts) { post in<br>                VStack(alignment: .leading) {<br>                    Text(post.title)<br>                        .font(.headline)<br>                    Text(post.body)<br>                        .font(.subheadline)<br>                        .foregroundColor(.secondary)<br>                }<br>            }<br>            .navigationTitle(&quot;Posts&quot;)<br>            .onAppear {<br>                viewModel.fetchPosts()<br>            }<br>            .alert(isPresented: $viewModel.showAlert) {<br>                Alert(<br>                    title: Text(&quot;Error&quot;),<br>                    message: Text(viewModel.errorMessage),<br>                    dismissButton: .default(Text(&quot;OK&quot;))<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>With these changes, your app now handles errors that may occur during the data fetching process. If an error occurs, the user is notified with an alert showing a descriptive message. This approach helps improve the user experience by keeping the user informed about what’s happening and how they might be able to remedy any issues (e.g., checking their internet connection).</p><p>Remember, error handling and user communication are critical aspects of creating robust and user-friendly apps. Always aim to handle errors gracefully and keep your users informed.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2ff12af9d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[List and ScrollView: Display collections of data using List or custom layouts with ScrollView.]]></title>
            <link>https://diegoperezsalas.medium.com/list-and-scrollview-display-collections-of-data-using-list-or-custom-layouts-with-scrollview-c475fdaf0e26?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c475fdaf0e26</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:49:23 GMT</pubDate>
            <atom:updated>2024-03-26T11:49:23.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>List</h3><p>A List in SwiftUI is used to present data in a scrollable list format, similar to UITableView in UIKit. It&#39;s highly efficient for displaying dynamic or static content because SwiftUI only renders the visible items on the screen, making it great for long lists of data.</p><p>Lists can be static, where you manually define the rows, or dynamic, where you use an array of data to generate rows. They support standard list behavior like selection, deletion, and moving items.</p><h4>Dynamic List Example</h4><p>Here’s how to create a dynamic list that displays an array of items:</p><pre>struct Item: Identifiable {<br>    let id = UUID()<br>    var name: String<br>}<br><br>struct ContentView: View {<br>    let items = [Item(name: &quot;Apple&quot;), Item(name: &quot;Banana&quot;), Item(name: &quot;Cherry&quot;)]<br><br>    var body: some View {<br>        List(items) { item in<br>            Text(item.name)<br>        }<br>    }<br>}</pre><p>Each item in the list needs to conform to the Identifiable protocol or you must provide a key path to a unique identifier using the .id() modifier on the List.</p><h4>List with Actions</h4><p>You can also add actions like deletion:</p><pre>struct ContentView: View {<br>    @State private var items = [Item(name: &quot;Apple&quot;), Item(name: &quot;Banana&quot;), Item(name: &quot;Cherry&quot;)]<br><br>    var body: some View {<br>        List {<br>            ForEach(items) { item inText(item.name)<br>}<br>.onDelete(perform: deleteItems)<br>}<br>.navigationBarItems(trailing: EditButton())<br>}<br>func deleteItems(at offsets: IndexSet) {<br>    items.remove(atOffsets: offsets)<br>}<br>}</pre><p>In this example, `.onDelete(perform:)` allows users to swipe to delete items from the list, and `EditButton()` provides a way to enter editing mode to delete or move items.</p><p>ScrollView `ScrollView` allows you to create custom scrollable layouts. Unlike `List`, it does not automatically recycle its views or provide list-specific interactions. `ScrollView` is ideal when you need more flexibility in arranging views or when you’re not displaying long lists of similar items.</p><p>ScrollView Example Here’s a simple `ScrollView` containing a vertical stack of text views:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        ScrollView {<br>            VStack(spacing: 20) {<br>                ForEach(1..&lt;100) { index in<br>                    Text(&quot;Item \(index)&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>ScrollView with Horizontal Scrolling</h3><p>You can also make ScrollView scroll horizontally:</p><pre>struct ContentView: View {<br>    var body: some View {<br>        ScrollView(.horizontal) {<br>            HStack(spacing: 20) {<br>                ForEach(1..&lt;100) { index in<br>                    Text(&quot;Item \(index)&quot;)<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Combining List and ScrollView</h3><p>While List is tailored for displaying a collection of similar data items, ScrollView provides more layout freedom. You might sometimes need to combine both in your app. For example, use a List for a main content area and a ScrollView for a custom, scrollable header or footer section.</p><h3>Conclusion</h3><p>Both List and ScrollView are powerful SwiftUI components for displaying content. Use List when you have a collection of similar data items to present in a standard list format with built-in support for common list interactions. Use ScrollView when you need more control over the layout or when displaying content that doesn&#39;t fit the standard list model. Experimenting with these components will give you a good feel for when to use each in your SwiftUI apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c475fdaf0e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation: Understand how to use NavigationView, NavigationLink, and TabView to navigate between…]]></title>
            <link>https://diegoperezsalas.medium.com/navigation-understand-how-to-use-navigationview-navigationlink-and-tabview-to-navigate-between-ba6ed5f18f4d?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6ed5f18f4d</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:33:11 GMT</pubDate>
            <atom:updated>2024-03-26T11:33:11.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>Navigation: Understand how to use NavigationView, NavigationLink, and TabView to navigate between different screens in your app.</h3><p>SwiftUI’s navigation components like NavigationView, NavigationLink, and TabView enable you to build complex navigational structures with ease. Let&#39;s dive into each component and see how they are used to navigate between different screens in your app.</p><h3>NavigationView</h3><p>NavigationView is a container view that enables navigation between views by pushing and popping views on a navigation stack. It&#39;s typically used to create hierarchical navigation interfaces, similar to the UINavigationController in UIKit.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        NavigationView {<br>            Text(&quot;Home Screen&quot;)<br>                .navigationTitle(&quot;Home&quot;)<br>        }<br>    }<br>}</pre><h3>NavigationLink</h3><p>NavigationLink is used within a NavigationView to push a new view onto the navigation stack, allowing users to navigate to a new screen. The destination is the view that you want to navigate to, and the label is what the user interacts with, like a button or a list item.</p><pre>NavigationView {<br>    List {<br>        NavigationLink(destination: DetailView()) {<br>            Text(&quot;Go to Detail View&quot;)<br>        }<br>    }<br>    .navigationTitle(&quot;Items&quot;)<br>}</pre><h3>DetailView Example</h3><p>Here’s a simple DetailView you might navigate to:</p><pre>struct DetailView: View {<br>    var body: some View {<br>        Text(&quot;This is the Detail View&quot;)<br>            .navigationTitle(&quot;Detail&quot;)<br>    }<br>}</pre><h3>TabView</h3><p>TabView is used to create a tabbed interface, allowing users to switch between different views by tapping on tabs usually displayed at the bottom of the screen. Each tab is represented by a TabView item, and you can associate an icon and a text label with each tab.</p><pre>TabView {<br>    ContentView()<br>        .tabItem {<br>            Label(&quot;Home&quot;, systemImage: &quot;house&quot;)<br>        }<br><br>    Text(&quot;Profile Screen&quot;)<br>        .tabItem {<br>            Label(&quot;Profile&quot;, systemImage: &quot;person&quot;)<br>        }<br>}</pre><h3>Combining NavigationView and TabView</h3><p>It’s common to combine NavigationView and TabView to create a tabbed app where each tab has its own navigation stack. Here’s a basic structure:</p><pre>TabView {<br>    NavigationView {<br>        ContentView()<br>    }<br>    .tabItem {<br>        Label(&quot;Home&quot;, systemImage: &quot;house&quot;)<br>    }<br><br>    NavigationView {<br>        Text(&quot;Profile Screen&quot;)<br>            .navigationTitle(&quot;Profile&quot;)<br>    }<br>    .tabItem {<br>        Label(&quot;Profile&quot;, systemImage: &quot;person&quot;)<br>    }<br>}</pre><h3>Practical Example: A Basic Navigation App</h3><p>Let’s create a basic app with two tabs: “Home” and “Profile”, where “Home” has a button to navigate to a detail view.</p><pre>// Main App Entry<br>@main<br>struct YourApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            AppTabView()<br>        }<br>    }<br>}<br><br>// TabView<br>struct AppTabView: View {<br>    var body: some View {<br>        TabView {<br>            NavigationView {<br>                HomeView()<br>            }<br>            .tabItem {<br>                Label(&quot;Home&quot;, systemImage: &quot;house&quot;)<br>            }<br><br>            Text(&quot;Profile Screen&quot;)<br>                .tabItem {<br>                    Label(&quot;Profile&quot;, systemImage: &quot;person&quot;)<br>                }<br>        }<br>    }<br>}<br><br>// HomeView with NavigationLink<br>struct HomeView: View {<br>    var body: some View {<br>        VStack {<br>            NavigationLink(destination: DetailView()) {<br>                Text(&quot;Go to Detail View&quot;)<br>            }<br>            .navigationTitle(&quot;Home&quot;)<br>        }<br>    }<br>}<br><br>// DetailView<br>struct DetailView: View {<br>    var body: some View {<br>        Text(&quot;Detail View Content&quot;)<br>            .navigationTitle(&quot;Detail&quot;)<br>    }<br>}</pre><h3>Conclusion</h3><p>NavigationView and NavigationLink allow for hierarchical navigation, while TabView is excellent for organizing different app sections at the same root level. Combining these elements thoughtfully can lead to intuitive and easy-to-navigate apps. Experiment with these components to understand their behavior and how they might fit best within your app&#39;s navigation structure.</p><h3><strong>Other Articles:</strong></h3><h4><a href="https://medium.com/@diegoperezsalas/creating-a-main-menu-in-swiftui-166cdc7c7c57">Creating a Main Menu in SwiftUI</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6ed5f18f4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How in Swift declare global variables or use shared data management approaches to use data across…]]></title>
            <link>https://diegoperezsalas.medium.com/how-in-swift-declare-global-variables-or-use-shared-data-management-approaches-to-use-data-across-a95ad2e00153?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a95ad2e00153</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:23:48 GMT</pubDate>
            <atom:updated>2024-03-26T11:23:48.129Z</atom:updated>
            <content:encoded><![CDATA[<h3>How in Swift declare global variables or use shared data management approaches to use data across your entire app!</h3><p>Here are four ways to declare global variables or use shared data management approaches to use data across your entire app:</p><h3>1. Global Variables</h3><p>You can simply declare a variable outside of any struct or class at the top level of your Swift file, making it accessible from anywhere in your app. However, this approach is generally discouraged for non-constant data due to issues with data management, testing, and debugging.</p><pre>var globalCounter: Int = 0</pre><h3>2. Singleton Pattern</h3><p>A more controlled way to have app-wide accessible data is using the Singleton pattern. A Singleton class ensures that only one instance of a class is created and provides a global access point to that instance. It’s commonly used for managing shared resources or settings.</p><pre>class AppData {<br>    static let shared = AppData()<br>    var counter: Int = 0<br><br>    private init() {} // Prevents others from creating instances<br>}</pre><p>To access or modify the counter from anywhere, you would use AppData.shared.counter.</p><h3>3. EnvironmentObject</h3><p>In SwiftUI, @EnvironmentObject is a property wrapper that allows you to share an observable object among all views in the app without having to pass it explicitly through each view. This is especially useful for data or settings that are used across many parts of your app.</p><p>First, create an observable class that conforms to ObservableObject:</p><pre>class GlobalSettings: ObservableObject {<br>    @Published var counter: Int = 0<br>}</pre><p>Then, in your App struct, attach the object to the environment:</p><pre>@main<br>struct MyApp: App {<br>    var settings = GlobalSettings()<br><br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>                .environmentObject(settings)<br>        }<br>    }<br>}</pre><p>Views that need access to GlobalSettings can now declare an @EnvironmentObject property:</p><pre>struct SomeView: View {<br>    @EnvironmentObject var settings: GlobalSettings<br><br>    var body: some View {<br>        // Use `settings.counter` here<br>    }<br>}</pre><h3>4. @AppStorage and UserDefaults</h3><p>For simple data types, you might want to use @AppStorage, which provides a property wrapper for automatically reading and writing to the UserDefaults, making it persistent across app launches.</p><pre>struct ContentView: View {<br>    @AppStorage(&quot;counter&quot;) var counter: Int = 0<br><br>    var body: some View {<br>        // Use `counter` here<br>    }<br>}</pre><h3>Choosing the Right Approach</h3><ul><li>Use global variables for constants or configuration that doesn’t change.</li><li>The Singleton pattern is useful for shared resources or services, like a network manager.</li><li>EnvironmentObject is ideal for shared data that needs to be observed across many views.</li><li>@AppStorage and UserDefaults are suitable for storing user preferences or simple persistent data.</li></ul><p>Each method has its use cases, advantages, and drawbacks. Choosing the right approach depends on your specific needs, such as the type of data you’re sharing, how widely it’s used, and whether it needs to be observed for changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a95ad2e00153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between @State and @Binding]]></title>
            <link>https://diegoperezsalas.medium.com/difference-between-state-and-binding-e9e940e72acd?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9e940e72acd</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:13:31 GMT</pubDate>
            <atom:updated>2024-03-26T11:13:31.783Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the difference between @State and @Binding in SwiftUI is crucial for managing data flow in your apps effectively. Here&#39;s a breakdown of each and how they differ:</p><h3>@State</h3><ul><li>Purpose: @State is used to declare a source of truth for data within a single view. It&#39;s meant for simple data types that are local to the view. When the @State variable changes, SwiftUI automatically rerenders the part of the view that depends on this variable, allowing your UI to update in response to data changes.</li><li>Ownership: A @State property is owned by the view. This means the data is stored directly within the view, and the view controls the lifecycle of this data.</li><li>Privacy: Typically, @State variables are declared as private because they&#39;re intended to be accessed and modified only by the view that owns them. This encapsulation ensures that the view&#39;s state cannot be inadvertently changed from outside the view.</li><li>Usage: Use @State for temporary storage of app data in a view. It&#39;s suitable for simple UI state management, like toggling a button, entering text in a field, etc.</li></ul><h3>@Binding</h3><ul><li>Purpose: @Binding is used to create a two-way connection between a view and its parent or another view. It allows a view to read and write a state owned by another view without owning that state directly. When the data changes, both the original owner of the state and any views using a @Binding to that state are updated.</li><li>Ownership: A @Binding property does not own the data it refers to. Instead, it acts as a reference or a pointer to the state owned by another view. This approach allows multiple views to interact with the same piece of data.</li><li>Privacy: @Binding variables are typically passed into a view&#39;s initializer or as part of a view&#39;s configuration. They&#39;re meant to be set up by the parent or another view that owns the original source of truth (@State or other property wrappers like @ObservedObject, @EnvironmentObject, etc.).</li><li>Usage: Use @Binding when you need to modify a state from a different view than the one that owns it. This is common in custom components or child views that need to update shared data.</li></ul><h3>Key Differences</h3><ul><li>Ownership: @State is for state owned by the view itself, while @Binding is for accessing and mutating state owned by another view.</li><li>Control: @State gives a view control over its own data, ensuring that it can manage its UI state internally. @Binding allows a view to manipulate data owned elsewhere, facilitating communication between views.</li><li>Use Case: You use @State to manage a view&#39;s internal state and @Binding to allow a child or another view to update the state that&#39;s owned by a different view.</li></ul><h3>Example to Illustrate</h3><pre>struct ParentView: View {<br>    @State private var toggleStatus = false // Owned by ParentView<br><br>    var body: some View {<br>        ChildView(toggleStatus: $toggleStatus) // Passing a binding to ChildView<br>    }<br>}<br><br>struct ChildView: View {<br>    @Binding var toggleStatus: Bool // Reference to the state in ParentView<br><br>    var body: some View {<br>        Toggle(&quot;Enable feature&quot;, isOn: $toggleStatus)<br>    }<br>}</pre><p>In this example, ParentView owns the toggleStatus state. ChildView needs to update this state based on user interaction with a Toggle. By passing a @Binding to ChildView, both views stay in sync with the current toggleStatus.</p><p>This difference between @State and @Binding is foundational to managing state in SwiftUI applications, ensuring data consistency and reactive UI updates across your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e940e72acd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State and Binding: Learn how to manage state within your app to create dynamic and interactive UIs.]]></title>
            <link>https://diegoperezsalas.medium.com/state-and-binding-learn-how-to-manage-state-within-your-app-to-create-dynamic-and-interactive-uis-add8238d27a8?source=rss-83e6af1d58e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/add8238d27a8</guid>
            <dc:creator><![CDATA[Diego Perez Salas]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 11:10:45 GMT</pubDate>
            <atom:updated>2024-03-26T11:10:45.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is State?</h3><p>In SwiftUI, @State is a property wrapper that you use to declare state variables for simple data types that belong to a single view. When a state variable changes, SwiftUI automatically rerenders the view to reflect the change.</p><h3>What is Binding?</h3><p>Binding provides a two-way connection between a state variable and a view that displays or changes the value. It allows interactive controls like text fields, switches, sliders, etc., to read and write the state. You can create a binding from a state variable by prefixing it with a dollar sign $.</p><h3>Example: Counter App</h3><p>Let’s build a simple counter app that increases, decreases, or resets a number when the user taps a button.</p><h4>Step 1: Setup Your SwiftUI View</h4><p>Open your SwiftUI project and navigate to the ContentView.swift file. Replace its content with the following:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    // Declare a state variable<br>    @State private var count = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Count: \(count)&quot;)<br>                .font(.title)<br>                .padding()<br><br>            HStack {<br>                // Decrease Button<br>                Button(action: {<br>                    if count &gt; 0 { count -= 1 }<br>                }) {<br>                    Text(&quot;-&quot;)<br>                        .font(.title)<br>                        .frame(width: 50, height: 50)<br>                        .foregroundColor(.white)<br>                        .background(Color.red)<br>                        .clipShape(Circle())<br>                }<br><br>                // Reset Button<br>                Button(&quot;Reset&quot;) {<br>                    count = 0<br>                }<br>                .padding()<br>                .background(Color.gray)<br>                .foregroundColor(.white)<br>                .clipShape(RoundedRectangle(cornerRadius: 5))<br><br>                // Increase Button<br>                Button(action: {<br>                    count += 1<br>                }) {<br>                    Text(&quot;+&quot;)<br>                        .font(.title)<br>                        .frame(width: 50, height: 50)<br>                        .foregroundColor(.white)<br>                        .background(Color.green)<br>                        .clipShape(Circle())<br>                }<br>            }<br>            .padding()<br>        }<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h4>Explanation</h4><ul><li>@State private var count = 0: This line declares a state variable named count initialized to zero. The @State wrapper tells SwiftUI to watch this variable for changes.</li><li>The Text(&quot;Count: \(count)&quot;) view displays the current value of count.</li><li>The three buttons each perform different actions: decrease the count, reset it to zero, or increase it. The action closures modify the count state, triggering the view to update automatically.</li></ul><h3>Working with Binding</h3><p>Suppose you have a child view that needs to modify the count state. You can pass a binding to this child view. Here&#39;s a quick example:</p><h4>Child View</h4><pre>struct CounterControl: View {<br>    @Binding var count: Int<br><br>    var body: some View {<br>        Button(&quot;Increment&quot;) {<br>            count += 1<br>        }<br>        .padding()<br>        .background(Color.blue)<br>        .foregroundColor(.white)<br>        .clipShape(Circle())<br>    }<br>}</pre><h4>Update ContentView</h4><p>Add the CounterControl to your ContentView and pass a binding to count:</p><pre>CounterControl(count: $count)<br>    .padding()</pre><p>The $count syntax creates a binding to the count state variable, which allows CounterControl to update count directly.</p><p>Let’s create a comprehensive SwiftUI app example that demonstrates using @State for local state management and Binding to pass state data between views. We&#39;ll implement a simple counter app with a main view to display and control the counter and a child view for incrementing the counter.</p><h3>Step 1: The Child View (CounterControl.swift)</h3><p>Create a new SwiftUI View file named CounterControl.swift and replace its content with the following code. This view will have a button that, when tapped, increments the counter. It uses a Binding to allow changes made in this view to be reflected in the parent view&#39;s state.</p><pre>import SwiftUI<br><br>struct CounterControl: View {<br>    @Binding var count: Int // Binding to the count state from the parent view<br><br>    var body: some View {<br>        Button(&quot;Increment&quot;) {<br>            count += 1<br>        }<br>        .padding()<br>        .background(Color.blue)<br>        .foregroundColor(.white)<br>        .clipShape(Circle())<br>    }<br>}</pre><h3>Step 2: The Main View (ContentView.swift)</h3><p>Now, let’s use the CounterControl view in our main ContentView, allowing us to demonstrate both direct state manipulation within the ContentView and indirect manipulation via a child view (CounterControl) using Binding.</p><p>Replace the content in ContentView.swift with the following code:</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var count = 0 // State variable to hold the counter value<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            Text(&quot;Count: \(count)&quot;)<br>                .font(.title)<br><br>            HStack(spacing: 20) {<br>                // Decrease Button<br>                Button(action: {<br>                    if count &gt; 0 { count -= 1 }<br>                }) {<br>                    Image(systemName: &quot;minus.circle.fill&quot;)<br>                        .font(.largeTitle)<br>                        .foregroundColor(.red)<br>                }<br><br>                // Reset Button<br>                Button(&quot;Reset&quot;) {<br>                    count = 0<br>                }<br>                .foregroundColor(.white)<br>                .padding()<br>                .background(Color.gray)<br>                .clipShape(RoundedRectangle(cornerRadius: 5))<br><br>                // Increase Button<br>                Button(action: {<br>                    count += 1<br>                }) {<br>                    Image(systemName: &quot;plus.circle.fill&quot;)<br>                        .font(.largeTitle)<br>                        .foregroundColor(.green)<br>                }<br>            }<br><br>            // Increment button from the child view<br>            CounterControl(count: $count) // Pass a binding to the count<br>                .padding()<br>        }<br>        .padding()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h3>Explanation:</h3><ul><li>ContentView is the main view that contains a text displaying the current counter value and three buttons to decrease, reset, and increase the counter. It also includes the CounterControl as a child view.</li><li>The @State private var count = 0 declaration creates a state variable count that can be modified within this view.</li><li>The CounterControl(count: $count) line passes a binding of count to the CounterControl view. The $ prefix creates a binding to the count state variable, allowing the CounterControl view to update the count directly.</li></ul><p>This example demonstrates the power of @State and Binding in SwiftUI for creating dynamic and interactive UIs. Experiment with the code, perhaps by adding more functionality or more child views, to get a deeper understanding of how data flows in SwiftUI apps.</p><h3>Conclusion</h3><p>With these examples, you’ve seen how to use @State for local state management and how to create dynamic UIs that respond to user input. Additionally, you&#39;ve learned how to pass state data between parent and child views using Binding. Experimenting with these concepts will help you grasp the power of SwiftUI&#39;s data flow and build more complex and interactive apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=add8238d27a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>