<?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 Orfeas Iliopoulos on Medium]]></title>
        <description><![CDATA[Stories by Orfeas Iliopoulos on Medium]]></description>
        <link>https://medium.com/@OrfeasUK?source=rss-1e4608b513b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SyTwb9my0dtfLfwvr8cTSQ@2x.jpeg</url>
            <title>Stories by Orfeas Iliopoulos on Medium</title>
            <link>https://medium.com/@OrfeasUK?source=rss-1e4608b513b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:12:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@OrfeasUK/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[Using Global Actors Instead of Singletons for Thread Safety in Swift]]></title>
            <link>https://medium.com/@OrfeasUK/using-global-actors-instead-of-singletons-for-thread-safety-in-swift-3bfaa3119ceb?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bfaa3119ceb</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[structured-concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-6]]></category>
            <category><![CDATA[async-await-in-swift]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 13:03:07 GMT</pubDate>
            <atom:updated>2025-01-24T13:03:07.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-wOrDmVG-Gm2bFBxaI1wQ.jpeg" /></figure><p>In concurrent programming, ensuring thread safety is a crucial aspect of building robust and error-free applications. In Swift, the Singleton pattern has traditionally been a popular choice for managing shared state. However, Singletons come with limitations, particularly around thread safety. Starting with Swift 5.5, Global Actors offer an elegant alternative for managing shared resources while ensuring thread safety. This article explores the advantages of Global Actors and how to use them effectively in place of Singletons.</p><h4>Limitations of Singletons in Thread Safety</h4><p>Singletons are a design pattern where a class or object ensures a single instance exists and provides a global point of access to that instance. While convenient, they often require additional mechanisms, such as locks or queues, to ensure thread safety when accessed by multiple threads.</p><p>Common problems with Singletons include:<br>- **Complexity**: Manually synchronizing access to shared resources increases code complexity.<br>- **Error-prone**: Mismanagement of locks or queues can lead to issues like deadlocks, race conditions, or performance bottlenecks.<br>- **Testing challenges**: Singletons can hinder testing and dependency injection due to their global state.</p><h4>Example of a Thread-Safe Singleton</h4><pre>class Logger {<br>    static let shared = Logger()<br>    private let queue = DispatchQueue(label: &quot;LoggerQueue&quot;)<br><br>    private init() {}<br><br>    func log(_ message: String) {<br>        queue.async {<br>            print(&quot;Log: \(message)&quot;)<br>        }<br>    }<br>}</pre><p>While this implementation ensures thread safety using a dedicated <strong>DispatchQueue</strong>, it introduces additional boilerplate and potential for misuse.</p><h3>Introducing Global Actors</h3><p>Global Actors, introduced in Swift 5.5, leverage the power of Swift’s concurrency model to enforce thread-safe access to shared resources. A Global Actor is a custom actor marked with the <strong>@globalActor</strong> attribute, which provides a single execution context for all its members.</p><h4>Benefits of Global Actors</h4><p>- <strong>Automatic thread safety:</strong> The Swift runtime enforces exclusive access to the actor’s isolated state.Simpler code**: Global Actors eliminate the need for explicit synchronization mechanisms.<br>- <strong>Structured concurrency:</strong> They integrate seamlessly with Swift’s async/await syntax.</p><h3>Implementing Global Actors</h3><p>To demonstrate, let’s create a Global Actor for managing logging functionality.</p><h4><strong>Define a Global Actor</strong></h4><pre>@globalActor<br>actor LoggerActor {<br>    static let shared = LoggerActor()<br>}</pre><h4>Use the Global Actor for Thread-Safe Access</h4><pre>@LoggerActor<br>class Logger {<br>    private init() {}<br>    static let shared = Logger()<br><br>    func log(_ message: String) {<br>        print(&quot;Log: \(message)&quot;)<br>    }<br>}</pre><p>Here, the `<a href="http://twitter.com/LoggerActor">@LoggerActor</a>` annotation ensures that all access to the `Logger` class is performed within the actor’s context.</p><h4>Using the Global Actor</h4><p>With the actor in place, you can safely call its methods using Swift’s structured concurrency:</p><pre>func performTask() async {<br>    await Logger.shared.log(&quot;Task started&quot;)<br>    // Perform other asynchronous tasks<br>    await Logger.shared.log(&quot;Task completed&quot;)<br>}</pre><p>The `await` keyword ensures that interactions with `Logger` occur in a safe and serialized manner.</p><h3>Comparing Singletons and Global Actors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*aPfqHlPOsqoUCRtLKbPNyQ.png" /></figure><h3>Conclusion</h3><p>Global Actors provide a modern and robust alternative to Singletons for managing shared state in Swift. By leveraging structured concurrency and actor isolation, they simplify thread safety while integrating seamlessly with async/await. As Swift continues to evolve, adopting Global Actors can lead to cleaner, safer, and more maintainable code.</p><p>When designing your next Swift application, consider replacing traditional Singletons with Global Actors to take full advantage of Swift’s concurrency model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bfaa3119ceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing an APIClient with Combine and SwiftUI]]></title>
            <link>https://blog.devgenius.io/implementing-an-apiclient-with-combine-and-swiftui-e54954fa5917?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e54954fa5917</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 14:26:41 GMT</pubDate>
            <atom:updated>2023-04-17T16:59:09.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_xVVadtkIEItmp2Dxc93g.png" /></figure><h3>Combine</h3><p>Combine is a framework introduced by Apple in iOS 13 that provides a declarative way to handle asynchronous events and data streams. With Combine, we can create a functional and reactive approach to network requests.</p><h3>Generics</h3><p>Generics are a powerful feature of Swift that allows us to write code that can work with any type, as long as that type meets certain requirements. By using generics, we can write code that is more flexible and reusable.</p><h3>APIClient Implementation</h3><p>Let’s start by creating a protocol that defines the properties and methods that our API client will need to implement. This protocol will be generic and require that the client be initialized with a URL and a Codable type.</p><pre>protocol APIClient {<br>    var baseURL: URL { get }<br>    var session: URLSession { get }<br>    <br>    func fetch&lt;T: Codable&gt;(endpoint: Endpoint, completion: @escaping (Result&lt;T, Error&gt;) -&gt; Void)<br>}</pre><p>Our APIClient protocol defines three properties: baseURL, which is the base URL for all requests, session, which is the URLSession that will handle the requests, and fetch, which is the method that will fetch the data.</p><p>The fetch method takes an Endpoint as its argument, which represents the specific endpoint that we want to request, and a completion closure that will be called when the request is complete. The completion closure will return a Result type, which can be either a success with the requested Codable type or a failure with an Error.</p><p>Next, let’s create a concrete implementation of our APIClient protocol. This implementation will take care of creating and sending the URLRequest, handling the response, and decoding the data.</p><pre>class APIClientImpl: APIClient {<br>    let baseURL: URL<br>    let session: URLSession<br>    <br>    init(baseURL: URL, session: URLSession = .shared) {<br>        self.baseURL = baseURL<br>        self.session = session<br>    }<br>    <br>    func fetch&lt;T: Codable&gt;(endpoint: Endpoint, completion: @escaping (Result&lt;T, Error&gt;) -&gt; Void) {<br>        guard let request = endpoint.request(with: baseURL) else {<br>            completion(.failure(APIError.badRequest))<br>            return<br>        }<br>        <br>        session.dataTask(with: request) { data, response, error in<br>            if let error = error {<br>                completion(.failure(error))<br>                return<br>            }<br>            <br>            guard let httpResponse = response as? HTTPURLResponse,<br>                  (200...299).contains(httpResponse.statusCode) else {<br>                completion(.failure(APIError.invalidResponse))<br>                return<br>            }<br>            <br>            guard let data = data else {<br>                completion(.failure(APIError.invalidData))<br>                return<br>            }<br>            <br>            do {<br>                let decodedData = try JSONDecoder().decode(T.self, from: data)<br>                completion(.success(decodedData))<br>            } catch {<br>                completion(.failure(APIError.decodingError))<br>            }<br>        }.resume()<br>    }<br>}</pre><p>Our APIClientImpl class implements the APIClient protocol and provides a concrete implementation of the fetch method. The initializer takes a baseURL and an optional session parameter, which defaults to URLSession.shared.</p><p>The fetch method first creates a URLRequest using the endpoint and baseURL, and checks if the request is valid. If the request is not valid, it returns a failure with a badRequest APIError.</p><p>If the request is valid, it sends the request using the URLSession dataTask method. When the response is received, it checks if there was an error, and returns a failure with the error if there was one. It also checks if the response status code is between 200 and 299, indicating a successful response.</p><p>If the status code is not in this range, it returns a failure with an invalidResponse APIError.</p><p>If the response is successful, it checks if the data received is valid. If the data is not valid, it returns a failure with an invalidData APIError.</p><p>If the data is valid, it decodes the data using a JSONDecoder and returns a success with the decoded data. If there is an error during decoding, it returns a failure with a decodingError APIError.</p><h3>Presenter Implementation</h3><p>Next, let’s create a Presenter that will fetch the data and update the ViewModel. The Presenter will be responsible for handling the business logic and updating the ViewModel with the data received from the API.</p><pre>class MyPresenter&lt;T: Codable&gt;: ObservableObject {<br>    @Published var viewModel: MyViewModel&lt;T&gt;<br>    let apiClient: APIClient<br>    <br>    init(apiClient: APIClient, viewModel: MyViewModel&lt;T&gt;) {<br>        self.apiClient = apiClient<br>        self.viewModel = viewModel<br>    }<br>    <br>    func fetchData(for endpoint: Endpoint) {<br>        apiClient.fetch(endpoint: endpoint) { [weak self] result in<br>            switch result {<br>            case .success(let data):<br>                DispatchQueue.main.async {<br>                    self?.viewModel.data = data<br>                }<br>            case .failure(let error):<br>                print(error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><p>Our MyPresenter class is generic, and takes a Codable type as its generic parameter. It also conforms to the ObservableObject protocol, and provides a published viewModel property that the view can observe. The initializer takes an APIClient parameter, a MyViewModel parameter, and sets them to the apiClient and viewModel properties, respectively.</p><p>The fetchData method uses the APIClient to fetch data, and updates the viewModel data property with the fetched data if the request is successful. It also prints the error if the request fails.</p><h3>ViewModel Implementation</h3><p>Now, let’s create a ViewModel that will handle the requests and provide an ObservableObject that the view can observe. The ViewModel will be responsible for storing the data received from the Presenter.</p><pre>class MyViewModel&lt;T: Codable&gt;: ObservableObject {<br>    @Published var data: T?<br>}</pre><p>Our MyViewModel class is generic, and takes a Codable type as its generic parameter. It also conforms to the ObservableObject protocol, and provides a published data property that the view can observe.</p><h3>View Implementation</h3><p>Finally, let’s create a View that will display the fetched data. The View will take a Presenter and a ViewModel as parameters, and use the Presenter to fetch the data and update the ViewModel.</p><pre>struct MyView&lt;T: Codable&gt;: View {<br>    @StateObject var presenter: MyPresenter&lt;T&gt;<br>    let viewModel: MyViewModel&lt;T&gt;<br>    let endpoint: Endpoint<br>    <br>    init(presenter: MyPresenter&lt;T&gt;, viewModel: MyViewModel&lt;T&gt;, endpoint: Endpoint) {<br>        self.presenter = presenter<br>        self.viewModel = viewModel<br>        self.presenter.viewModel = viewModel<br>        self.endpoint = endpoint<br>    }<br>    <br>    var body: some View {<br>        VStack {<br>            if let data = viewModel.data {<br>                // display the fetched data<br>            } else {<br>                // show loading spinner or error message<br>            }<br>        }<br>        .onAppear {<br>            presenter.fetchData(for: endpoint)<br>        }<br>    }<br>}</pre><p>Our MyView struct is generic, and takes a Codable type as its generic parameter. It takes a MyPresenter instance and a MyViewModel instance as its parameters, and creates a new instance of the MyViewModel.</p><p>In the body of the view, we check if the viewModel.data property is not nil, and display the fetched data if it is available. If the data is nil, we can display a loading spinner or an error message.</p><p>In the onAppear modifier, we call the fetchData method of the presenter, passing in the endpoint parameter.</p><h3>Usage</h3><p>Now that we have implemented all the necessary components, we can use them to fetch data from an API in our SwiftUI app.</p><p>Let’s say we want to fetch data from an API that returns an array of user objects. We would start by creating a Codable struct that represents the user object.</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}</pre><p>Next, we would create an Endpoint that represents the specific endpoint that we want to request.</p><pre>enum UserEndpoint {<br>    case getUsers<br>}<br><br>extension UserEndpoint: Endpoint {<br>    var path: String {<br>        switch self {<br>        case .getUsers:<br>            return &quot;/users&quot;<br>        }<br>    }<br>    <br>    var httpMethod: HTTPMethod {<br>        return .get<br>    }<br>}</pre><p>Our UserEndpoint enum conforms to the Endpoint protocol, and provides a path and httpMethod for the API request. In this case, we are requesting a list of users using a GET request.</p><p>Next, we would create an instance of the APIClientImpl using the base URL of the API.</p><pre>let apiClient = APIClientImpl(baseURL: URL(string: &quot;https://api.example.com&quot;)!)</pre><p>Finally, we can create an instance of the MyView and pass in the presenter, viewModel, and endpoint.</p><pre>MyView(presenter: presenter, viewModel: viewModel, endpoint: UserEndpoint.getUsers)</pre><p>This will create a view that will fetch the list of users and display them when the request is complete.</p><p>By using generics and Combine, we can create a flexible and reusable APIClient and ViewModel that can handle requests for any type of resource. By using a Presenter to fetch the data and update the ViewModel, we can further separate the concerns of our app and make our code more modular.</p><h3>Conclusion</h3><p>In this article, we have explored how to implement an APIClient for SwiftUI using Combine and Generics, along with a Presenter that fetches the data and updates the ViewModel. By using generics, we can write code that is more flexible and reusable. By using Combine, we can create a functional and reactive approach to network requests. And by using a Presenter to handle the business logic, we can further separate the concerns of our app and make our code more modular.</p><p>Implementing an APIClient in this way can save time and reduce errors by providing a standardized way of making API requests. It also makes it easier to handle errors and update the UI when data is received.</p><p>Overall, using Combine and Generics to implement an APIClient for SwiftUI can help make your code more flexible, reusable, and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e54954fa5917" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/implementing-an-apiclient-with-combine-and-swiftui-e54954fa5917">Implementing an APIClient with Combine and SwiftUI</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Combine]]></title>
            <link>https://blog.devgenius.io/introduction-to-combine-7f8a0e1dab09?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f8a0e1dab09</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 10:57:35 GMT</pubDate>
            <atom:updated>2023-04-14T19:27:37.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_xVVadtkIEItmp2Dxc93g.png" /></figure><p>In modern iOS development, reactive programming is a common approach for handling asynchronous events and data streams. One of the most popular reactive programming frameworks in the Apple ecosystem is Combine, which was introduced with iOS 13. Combine is a declarative Swift framework for processing values over time, providing a functional and reactive programming paradigm that allows for cleaner, more concise, and more maintainable code. In this article, we will explore the basics of Combine and demonstrate how it can be used to simplify asynchronous programming in Swift.</p><h3>Overview of Combine</h3><p>Combine is a framework that provides a set of operators and publishers for processing values over time. Publishers represent streams of data, while operators transform and combine these streams to create new streams. Subscribers receive and handle these streams of data. Publishers can emit three types of events: a value, a completion event, or an error event. Subscribers can react to these events and handle them in different ways.</p><p>Combine includes a number of built-in publishers and operators for working with different kinds of data streams, such as user interactions, network requests, and state changes. Publishers can be combined with operators to create complex streams of data, and subscribers can react to these streams by executing code in response to specific events.</p><h3>Example 1: Download a JSON file from a web API</h3><p>Let’s take a look at some code examples to see how Combine can be used in practice. In this example, we will use Combine to download a JSON file from a web API and decode it into a Swift struct.</p><p>First, we need to create a publisher that downloads the JSON data from the web API:</p><pre>import Combine<br><br>func downloadJson(from url: URL) -&gt; AnyPublisher&lt;Data, Error&gt; {<br>    URLSession.shared.dataTaskPublisher(for: url)<br>        .map(\.data)<br>        .eraseToAnyPublisher()<br>}</pre><p>This code defines a function downloadJson that takes a URL as input and returns a AnyPublisher&lt;Data, Error&gt;. The function uses the dataTaskPublisher(for:) method of the URLSession class to create a publisher that downloads the data from the given URL. The map(\.data) operator is used to extract the data property from the URLSession.DataTaskPublisher.Output type, which is a tuple containing the downloaded data and the response. The eraseToAnyPublisher() operator is used to erase the type of the publisher, allowing it to be used as a AnyPublisher&lt;Data, Error&gt;.</p><p>Next, we define a struct that represents the data we want to decode:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}</pre><p>This struct conforms to the Codable protocol, which allows us to decode JSON data into an instance of this struct.</p><p>Finally, we can use the downloadJson function to download the JSON data, and then decode it into an instance of the User struct:</p><pre>let url = URL(string: &quot;https://jsonplaceholder.typicode.com/users/1&quot;)!<br>downloadJson(from: url)<br>    .decode(type: User.self, decoder: JSONDecoder())<br>    .sink(<br>        receiveCompletion: { completion in<br>            switch completion {<br>            case .finished:<br>                print(&quot;Download complete&quot;)<br>            case .failure(let error):<br>                print(&quot;Error: \(error)&quot;)<br>            }<br>        },<br>        receiveValue: { user in<br>            print(&quot;User: \(user)&quot;)<br>        }<br>    )</pre><p>This code downloads the JSON data from the given URL using the downloadJson function, and then uses the decode operator to decode the JSON data into an instance of the User struct. The sink subscriber is used to handle the events emitted by the publisher. The receiveCompletion closure handles the completion event, which can either be a successful completion or an error. The receiveValue closure handles the successful completion event and receives the decoded User object as its parameter. In this example, we simply print the user object to the console.</p><h3>Example 2: Combine and UIKit</h3><p>Combine can be used with UIKit to handle user interactions, network requests, and state changes in your app. Here’s an example of using Combine to handle a button tap event:</p><pre>let button = UIButton(type: .system)<br>button.setTitle(&quot;Tap me&quot;, for: .normal)<br><br>button.publisher(for: .touchUpInside)<br>    .sink { _ in<br>        print(&quot;Button tapped&quot;)<br>    }</pre><p>This code creates a UIButton and sets its title. The publisher(for:) method is then used to create a publisher that emits events when the button is tapped. The sink subscriber is used to handle these events and print a message to the console.</p><h3>Example 3: Combine and Core Data</h3><p>Combine can also be used with Core Data to handle changes to your app’s data store. Here’s an example of using Combine to observe changes to a managed object context:</p><pre>let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)<br><br>NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave, object: context)<br>    .sink { notification in<br>        print(&quot;Changes saved to context&quot;)<br>    }</pre><p>This code creates a NSManagedObjectContext and sets up a publisher to observe changes to the context. The sink subscriber is used to handle these events and print a message to the console when changes are saved.</p><h3>Example 4: Combine and SwiftUI</h3><p>Combine is a core part of SwiftUI and can be used to handle state changes and animations in your app. Here’s an example of using Combine to animate a view:</p><pre>@State var isAnimating = false<br><br>let animation = Animation.easeInOut(duration: 2.0)<br>    .repeatForever(autoreverses: true)<br><br>Button(&quot;Animate&quot;) {<br>    isAnimating = true<br>}<br>.frame(width: 100, height: 100)<br>.background(Color.blue)<br>.cornerRadius(50)<br>.scaleEffect(isAnimating ? 1.5 : 1.0)<br>.animation(animation)</pre><p>This code uses a @State variable to control whether the view should be animated or not. When the button is tapped, the isAnimating variable is set to true, which triggers the animation. The scaleEffect modifier is used to apply a scale transformation to the view, and the animation modifier is used to apply the animation to the scale transformation.</p><h3>Conclusion</h3><p>Combine is a powerful and flexible framework for handling asynchronous events and data streams in Swift. It provides a declarative and reactive programming paradigm that can simplify complex asynchronous programming tasks, making code easier to read, write, and maintain. By using Combine, developers can create more efficient, reliable, and scalable applications that can handle a wide range of asynchronous events and data streams.</p><p>In this article, we covered the basics of Combine. We explored the different types of operators and publishers that Combine provides, and how they can be used to create complex streams of data. With this knowledge, you should be able to start using Combine in your own projects and take advantage of its powerful reactive programming capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f8a0e1dab09" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/introduction-to-combine-7f8a0e1dab09">Introduction to Combine</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing an API client with Swift’s async/await]]></title>
            <link>https://blog.devgenius.io/implementing-an-api-client-with-swifts-async-await-7bcd95c59d3c?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcd95c59d3c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 10:47:45 GMT</pubDate>
            <atom:updated>2023-04-05T12:17:27.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSzwnpIFsmpBDH56Nn3GEg.png" /><figcaption>Async/await</figcaption></figure><p>Implementing an API client with Swift’s async/await functionality can greatly improve the performance and user experience of an iOS app. In this article, we will be implementing a Repository class that handles API calls and returns a model and error using async/await. We will use a public RSS feed using JSON as an example API.</p><h3>Step 1: Create the Repository Protocol</h3><p>Before implementing the Repository class, we need to define the Repository protocol. This will define the methods that the Repository class will implement. Create a new Swift file and add the following code:</p><pre>import Foundation<br><br>enum Result&lt;T, E&gt; {<br>    case success(T)<br>    case failure(E)<br>}<br><br>enum MyError: Error {<br>    case failed(String?)<br>    case unknown<br>    case notMapped(String?)<br>}<br><br>protocol Repository {<br>    func execute&lt;T: Decodable&gt;(endpoint: Endpoint, pathToDecode: String?) async -&gt; Result&lt;T?, MyError&gt;<br>}<br><br>extension Repository {<br>    func execute&lt;T: Decodable&gt;(endpoint: Endpoint, pathToDecode: String? = nil) async -&gt; Result&lt;T?, MyError&gt; where T: Decodable {<br>        await execute(endpoint: endpoint, pathToDecode: pathToDecode)<br>    }<br>}</pre><p>In this protocol, we define two associated types T and E for the Result enum. T represents the success case, which will contain the decoded model, and E represents the failure case, which will contain an error of type MyError. We also define the Repository protocol with a single method execute that takes an Endpoint object and an optional pathToDecode string, and returns a Result object containing a decoded model or an error.</p><h3>Step 2: Create the Endpoint Struct</h3><p>Next, we need to create the Endpoint struct that will hold the information about the API endpoint we want to call. Create a new Swift file and add the following code:</p><pre>import Foundation<br><br>struct Endpoint {<br>    enum RequestType: String {<br>        case get = &quot;GET&quot;<br>        case post = &quot;POST&quot;<br>    }<br><br>    let url: URL<br>    let requestType: RequestType<br>    let parameters: [String: Any]?<br>    let headers: [String: Any]?<br>    <br>    func createHeaders() -&gt; [String: Any] {<br>        var headers = [&quot;Content-Type&quot;: &quot;application/json&quot;]<br>        if let additionalHeaders = self.headers {<br>            for header in additionalHeaders {<br>                headers[header.key] = header.value<br>            }<br>        }<br>        return headers<br>    }<br>}</pre><p>In this struct, we define the properties url, requestType, parameters, and headers. We also define an init method that takes these properties as arguments. We define an enum for the HTTP request type with two cases, get and post. We also define a method createHeaders that returns a dictionary of headers for the request.</p><h3>Step 3: Create the Repository Implementation Class</h3><p>With the protocol and endpoint struct defined, we can now create the RepositoryImpl class that implements the Repository protocol. Create a new Swift file and add the following code:</p><pre>final class RepositoryImpl: Repository {<br>    // The decoder used to decode the JSON responses.<br>    let decoder: JSONDecoder<br>    <br>    // Initializes the repository with an optional custom decoder and cache size configurations.<br>    init(decoder: JSONDecoder? = nil,<br>         diskCapacity: Int = 60*1024*1024,<br>         memoryCapacity: Int = 90*1024*1024) {<br>        <br>        // Sets the cache size for the URL cache shared instance.<br>        URLSession.shared.configuration.urlCache?.diskCapacity = diskCapacity<br>        URLSession.shared.configuration.urlCache?.memoryCapacity = memoryCapacity<br><br>        // If a custom decoder is provided, sets it as the repository&#39;s decoder with the same key decoding strategy.<br>        // Otherwise, creates a default decoder with a snake case key decoding strategy.<br>        guard let decoder = decoder else {<br>            self.decoder = JSONDecoder()<br>            self.decoder.keyDecodingStrategy = .convertFromSnakeCase<br>            <br>            return<br>        }<br>        self.decoder = decoder<br>        self.decoder.keyDecodingStrategy = decoder.keyDecodingStrategy<br>    }<br>    <br>    // Executes the API request with the given endpoint and decodes the response into the specified model type.<br>    func execute&lt;T: Decodable&gt;(endpoint: Endpoint, pathToDecode: String? = nil) async -&gt; Result&lt;T?, MyError&gt; {<br>        <br>        // Creates a URL request with the endpoint&#39;s URL and sets the cache policy and request type.<br>        var urlRequest = URLRequest(url: endpoint.url)<br>        urlRequest.cachePolicy = .returnCacheDataElseLoad<br>        urlRequest.httpMethod = endpoint.requestType.rawValue<br>        <br>        // If the endpoint has parameters, serializes them to JSON and sets them as the request body.<br>        if let parameters = endpoint.parameters {<br>            urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: parameters)<br>        }<br><br>        // Sets the headers for the request.<br>        endpoint.createHeaders().forEach { (key, value) in<br>            if let value = value as? String {<br>                urlRequest.setValue(value, forHTTPHeaderField: key)<br>            }<br>        }<br>        <br>        // Checks if there is a cached response for the request.<br>        if let cachedResponse = URLSession.shared.configuration.urlCache?.cachedResponse(for: urlRequest),<br>            let httpResponse = cachedResponse.response as? HTTPURLResponse {<br>            // If there is a cached response, decodes the data and returns it as a success result.<br>            let (data, response) = (cachedResponse.data, httpResponse)<br>            <br>            return await decodeResponse(data: data, response: response, pathToDecode: pathToDecode)<br>        }<br><br>        do {<br>            // Performs the API request and decodes the data from the response into the specified model type.<br>            let (data, response) = try await URLSession.shared.data(for: urlRequest)<br>            <br>            return await decodeResponse(data: data, response: response, pathToDecode: pathToDecode)<br><br>        } catch(let error) {<br>            // If an error occurs, returns it as a failure result.<br>            return .failure(.failed(error.localizedDescription))<br>        }<br>    }<br>    <br>    // Decodes the data from the API response into the specified model type.<br>    private func decodeResponse&lt;T: Decodable&gt;(data: Data, response: URLResponse, pathToDecode: String? = nil) async -&gt; Result&lt;T?, MyError&gt; {<br>        // Checks if the API response status code is within the success range (200-299).<br>        guard let httpResponse = response as? HTTPURLResponse,<br>              (200..&lt;300).contains(httpResponse.statusCode)  else {<br>            return .failure(.unknown)<br>        }<br>        <br>        var model: T?<br>        do {<br>        var jsonObject: Any?<br>        if let pathToDecode = pathToDecode,<br>           let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [AnyHashable: Any] {<br>            if let arr = dict[pathToDecode] as? Array&lt;Any&gt; {<br>                jsonObject = arr<br>            } else if let dic = dict[pathToDecode] as? [String: Any] {<br>                jsonObject = dic<br>            }<br>            <br>            guard let jsonObject = jsonObject,<br>                  let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: []) else {<br>                return .failure(.notMapped(nil))<br>            }<br>            model = try decoder.decode(T.self, from: jsonData)<br>        } else {<br>            model = try decoder.decode(T.self, from: data)<br>        }<br>        <br>        return .success(model)<br><br>    } catch(let error) {<br>        print(error)<br>        return .failure(.failed(error.localizedDescription))<br>    }<br>}</pre><p>Once the API call is made, and the response has been successfully decoded, you can handle the response as per your requirement. In the above code, we have used a Result type to encapsulate the success and failure cases of the API call.</p><p>In the execute function, we first check if there is a cached response available for the request. If there is a cached response, we return the decoded response as a success result. If there is no cached response, we perform the API call using URLSession.shared.data(for:) function and decode the response.</p><p>In the decodeResponse function, we first check if the HTTP status code is within the success range (200-299). If it is, we decode the response data into the specified model type and return it as a success result. If there is an error in decoding the response data, we return it as a failure result.</p><h3>Example</h3><p>Let’s say you want to fetch a list of articles from a public RSS feed using the RepositoryImpl class. First, you need to define the Endpoint for the API call.</p><pre>struct RSSFeedEndpoint: Endpoint {<br>    let url: URL<br>    let requestType: RequestType = .get<br>    let parameters: [String: Any]? = nil<br>    <br>    init(feedURL: URL) {<br>        self.url = feedURL<br>    }<br>    <br>    func createHeaders() -&gt; [String: Any]? {<br>        return nil<br>    }<br>}</pre><p>Next, you can create the Feed struct.</p><pre>struct Feed: Codable {<br>    let title: String<br>    let link: String<br>    let updated: String<br>    let entry: [FeedItem]<br>}<br><br>struct FeedItem: Codable {<br>    let title: String<br>    let updated: String<br>    let content: String<br>    let author: String?<br>    let category: [String]?   <br>}</pre><p>Next, you can create an instance of the RepositoryImpl class and use it to fetch the list of articles.</p><pre>let repository = RepositoryImpl()<br><br>async {<br>    let endpoint = RSSFeedEndpoint(feedURL: URL(string: &quot;https://www.apple.com/newsroom/rss-feed.rss&quot;)!)<br>    let result: Result&lt;Feed?, MyError&gt; = await repository.execute(endpoint: endpoint, pathToDecode: &quot;feed&quot;)<br><br>    switch result {<br>    case .success(let feed):<br>        // Do something with the fetched feed.<br>        print(feed)<br>    case .failure(let error):<br>        // Handle the error.<br>        print(error)<br>    }<br>}</pre><p>In the above code, we create an instance of the RepositoryImpl class and use it to fetch the RSS feed from the provided URL. Once the API call is completed, we switch on the Result type and handle the success and failure cases.</p><p>If the API call is successful, we can access the fetched feed using the feed parameter. If there is an error, we can handle it using the error parameter.</p><h3>Conclusion</h3><p>In this article, we learned how to implement an API call using the Repository design pattern in an iOS app using async/await and a public RSS feed using JSON. We walked through the step-by-step process of implementing the RepositoryImpl class, which handles the API call and returns a model and error using the Result type.</p><p>We started by defining the Endpoint protocol, which encapsulates the API request details, followed by implementing the Repository protocol, which defines the functions required to perform the API call.</p><p>We then implemented the RepositoryImpl class, which conforms to the Repository protocol and handles the API call using the URLSession class. We also added caching to the API call and provided a custom decoder for decoding the JSON response.</p><p>Finally, we demonstrated how to use the RepositoryImpl class to fetch a list of articles from a public RSS feed using async/await and handle the response using the Result type.</p><p>By implementing the Repository design pattern, you can keep your networking code separate from your business logic, making it easier to maintain and test your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcd95c59d3c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/implementing-an-api-client-with-swifts-async-await-7bcd95c59d3c">Implementing an API client with Swift’s async/await</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured concurrency in Swift]]></title>
            <link>https://blog.devgenius.io/structured-concurrency-in-swift-1460c37576b3?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1460c37576b3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 11:34:55 GMT</pubDate>
            <atom:updated>2023-04-05T19:05:51.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aI519OW9TBBT_JtftcnTDw.jpeg" /></figure><h3>Introduction</h3><p>Concurrency is a technique used in programming to achieve parallelism and improve the performance of applications. Swift provides various mechanisms for concurrency, including threads, queues, and actors. In this article, we’ll explore structured concurrency, a new approach to concurrency that provides a safer and more efficient way of managing tasks in Swift.</p><h3>What is Structured Concurrency?</h3><p>Structured concurrency is a programming paradigm that emphasizes the importance of handling tasks in a structured and hierarchical manner. In structured concurrency, tasks are organized in a tree-like structure, where each task depends on its parent task. The parent task is responsible for creating, managing, and canceling its child tasks. This approach helps to prevent errors and memory leaks by ensuring that all tasks are properly managed and executed.</p><h3>Implementing Structured Concurrency in Swift</h3><p>In Swift, structured concurrency is implemented using the async/await syntax, which allows you to write asynchronous code in a synchronous style. With async/await, you can write code that looks and behaves like regular synchronous code, but still runs asynchronously in the background.</p><p>Let’s take a look at an example. Suppose we have a function called downloadImage that downloads an image from a remote server. We want to call this function asynchronously and display the downloaded image in a UIImageView once the download is complete.</p><pre>func downloadImage(url: URL) async -&gt; UIImage? {<br>    let data = try? Data(contentsOf: url)<br>    let image = UIImage(data: data ?? Data())<br>    return image<br>}<br><br>let url = URL(string: &quot;https://example.com/image.png&quot;)!<br>let image = await downloadImage(url: url)<br><br>if let image = image {<br>    imageView.image = image<br>}</pre><p>In this example, we define the downloadImage function using the async keyword, which indicates that the function is an asynchronous operation. We use the try? keyword to handle any errors that may occur during the download. Finally, we use the await keyword to wait for the download to complete before assigning the downloaded image to the UIImageView.</p><h3>Managing Child Tasks in Structured Concurrency</h3><p>In structured concurrency, child tasks are created and managed by their parent task. This ensures that all child tasks are properly managed and executed, and prevents errors and memory leaks.</p><p>Let’s take a look at an example. Suppose we have a function called downloadImages that downloads multiple images from a remote server. We want to download the images in parallel and display them in a UICollectionView once all the downloads are complete.</p><pre>func downloadImages(urls: [URL]) async -&gt; [UIImage?] {<br>    let images = await withTaskGroup(of: UIImage?.self) { group in<br>        for url in urls {<br>            group.async {<br>                let data = try? Data(contentsOf: url)<br>                let image = UIImage(data: data ?? Data())<br>                return image<br>            }<br>        }<br>    }<br><br>    return images<br>}<br><br>let urls = [<br>    URL(string: &quot;https://example.com/image1.png&quot;)!,<br>    URL(string: &quot;https://example.com/image2.png&quot;)!,<br>    URL(string: &quot;https://example.com/image3.png&quot;)!,<br>]<br><br>let images = await downloadImages(urls: urls)<br><br>collectionView.reloadData()</pre><p>In this example, we define the downloadImages function using the async keyword and use the withTaskGroup function to create a task group. We loop through the urls array and use the group.async function to create a child task for each URL. Finally, we use the await keyword to wait for all the child tasks to complete and return the downloaded images as an array.</p><h3>Conclusion</h3><p>Structured concurrency is a new approach to concurrency that provides a safer and more efficient way of managing tasks in Swift. By organizing tasks in a tree-like structure and allowing tasks to depend on their parent tasks, structured concurrency helps to prevent errors and memory leaks, and ensures that all tasks are properly managed and executed.</p><p>In this article, we explored the async/await syntax in Swift, which allows you to write asynchronous code in a synchronous style. We also looked at how to manage child tasks using the withTaskGroup function, which creates a task group for a set of related tasks and waits for all the tasks to complete before returning the results.</p><p>Structured concurrency is a powerful tool that can help you write more efficient and maintainable code. By using the async/await syntax and task groups, you can easily manage and execute asynchronous tasks in a structured and hierarchical manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1460c37576b3" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/structured-concurrency-in-swift-1460c37576b3">Structured concurrency in Swift</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SOLID principles in Swift]]></title>
            <link>https://medium.com/@OrfeasUK/implementing-solid-principles-in-swift-e60e4cd5aec6?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60e4cd5aec6</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 12:08:40 GMT</pubDate>
            <atom:updated>2023-04-19T12:05:52.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEDK9gmKUDr6hQ7t73zzXw.png" /></figure><p>SOLID is a set of principles that can help you write maintainable, scalable, and testable code. SOLID stands for:</p><ul><li>Single Responsibility Principle (SRP)</li><li>Open-Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP)</li><li>Dependency Inversion Principle (DIP)</li></ul><p>In this article, we’ll take a look at each of these principles and show you how to implement them in Swift.</p><h3>Single Responsibility Principle (SRP)</h3><p>The Single Responsibility Principle (SRP) states that a class should have only one reason to change. In other words, a class should have only one responsibility.</p><p>Let’s take a look at an example. Suppose we have a User class that has both authentication and data retrieval responsibilities.</p><pre>class User {<br>    func authenticate() {<br>        // ...<br>    }<br><br>    func getUserData() -&gt; UserData {<br>        // ...<br>    }<br>}</pre><p>This violates the SRP because the User class has two responsibilities: authentication and data retrieval. To fix this, we can create two new classes, Authenticator and UserDataRetriever, and move the responsibilities to these new classes.</p><pre>class Authenticator {<br>    func authenticate() {<br>        // ...<br>    }<br>}<br><br>class UserDataRetriever {<br>    func getUserData() -&gt; UserData {<br>        // ...<br>    }<br>}</pre><p>Now, the User class only needs to use these new classes to fulfill its responsibilities.</p><pre>class User {<br>    let authenticator = Authenticator()<br>    let userDataRetriever = UserDataRetriever()<br><br>    func authenticate() {<br>        authenticator.authenticate()<br>    }<br><br>    func getUserData() -&gt; UserData {<br>        return userDataRetriever.getUserData()<br>    }<br>}</pre><h3>Open-Closed Principle (OCP)</h3><p>The Open-Closed Principle (OCP) states that a class should be open for extension but closed for modification. In other words, you should be able to add new functionality to a class without modifying its existing code.</p><p>Let’s take a look at an example. Suppose we have a Product class that has a calculatePrice method that calculates the price of a product.</p><pre>class Product {<br>    var price: Double = 0.0<br><br>    func calculatePrice() {<br>        // ...<br>    }<br>}</pre><p>Now, suppose we want to add a discount feature to the Product class. We could modify the existing calculatePrice method to include the discount calculation, but this violates the OCP because we&#39;re modifying the existing code. To fix this, we can create a new Discount class and pass it to the Product class.</p><pre>protocol Discount {<br>    func calculateDiscountedPrice(originalPrice: Double) -&gt; Double<br>}<br><br>class Product {<br>    var price: Double = 0.0<br><br>    func calculatePrice(discount: Discount) -&gt; Double {<br>        let originalPrice = price<br>        let discountedPrice = discount.calculateDiscountedPrice(originalPrice: originalPrice)<br>        return discountedPrice<br>    }<br>}<br><br>class PercentageDiscount: Discount {<br>    let percentage: Double<br><br>    init(percentage: Double) {<br>        self.percentage = percentage<br>    }<br><br>    func calculateDiscountedPrice(originalPrice: Double) -&gt; Double {<br>        let discountedPrice = originalPrice - (originalPrice * (percentage / 100))<br>        return discountedPrice<br>    }<br>}</pre><p>Now, we can pass an instance of the PercentageDiscount class to the calculatePrice method of the Product class to get the discounted price.</p><pre>let product = Product()<br>product.price = 100.0<br><br>let discount = PercentageDiscount(percentage: 20.0)<br>let discountedPrice = product.calculatePrice(discount: discount)<br><br>print(discountedPrice) // Output: 80.0</pre><h3>Liskov Substitution Principle (LSP)</h3><p>The Liskov Substitution Principle (LSP) states that a derived class should be substitutable for its base class without affecting the correctness of the program. In other words, if you have a reference to a base class, you should be able to substitute a derived class without breaking the program.</p><p>Let’s take a look at an example. Suppose we have a Rectangle class that has width and height properties and a calculateArea method.</p><pre>class Rectangle {<br>    var width: Double<br>    var height: Double<br><br>    init(width: Double, height: Double) {<br>        self.width = width<br>        self.height = height<br>    }<br><br>    func calculateArea() -&gt; Double {<br>        return width * height<br>    }<br>}</pre><p>Now, suppose we want to add a Square class that is a special case of the Rectangle class where the width and height are always the same. We can create a Square class that inherits from the Rectangle class and override the width and height properties to always be the same.</p><pre>class Square: Rectangle {<br>    override var width: Double {<br>        didSet {<br>            height = width<br>        }<br>    }<br><br>    override var height: Double {<br>        didSet {<br>            width = height<br>        }<br>    }<br><br>    init(side: Double) {<br>        super.init(width: side, height: side)<br>    }<br>}</pre><p>Now, we can create an instance of the Square class and pass it to a method that expects a Rectangle object.</p><pre>func printArea(rectangle: Rectangle) {<br>    let area = rectangle.calculateArea()<br>    print(&quot;Area: \(area)&quot;)<br>}<br><br>let square = Square(side: 10.0)<br>printArea(rectangle: square)</pre><p>This works because the Square class is substitutable for the Rectangle class without affecting the correctness of the program.</p><h3>Interface Segregation Principle (ISP)</h3><p>The Interface Segregation Principle (ISP) states that a class should not be forced to depend on methods it does not use. In other words, you should separate large interfaces into smaller and more specific ones.</p><p>Let’s take a look at an example. Suppose we have a Printer protocol that has a print method.</p><pre>protocol Printer {<br>    func print()<br>}</pre><p>Now, suppose we want to create a ScannerPrinter class that implements both Scanner and Printer functionality. We could implement the print method for the ScannerPrinter class, but this violates the ISP because the ScannerPrinter class should not be forced to depend on the print method.</p><p>To fix this, we can create two new protocols, Scanner and Printer, and make the ScannerPrinter class conform to both protocols.</p><pre>protocol Scanner {<br>    func scan()<br>}<br><br>protocol Printer {<br>    func print()<br>}<br><br>class ScannerPrinter: Scanner, Printer {<br>    func scan() {<br>        // ...<br>    }<br><br>    func print() {<br>        // ...<br>    }<br>}</pre><p>Now, the ScannerPrinter class only depends on the methods it uses and not on the methods it doesn&#39;t use.</p><h3>Dependency Inversion Principle (DIP)</h3><p>The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules. Instead, they should both depend on abstractions. In other words, you should depend on interfaces, not implementations.</p><p>Let’s take a look at an example. Suppose we have a DataFetcher class that retrieves data from a remote server.</p><pre>protocol DataFetching {<br>    func fetchData(from url: URL) -&gt; Data?<br>}<br><br>class DataFetcher: DataFetching {<br>    func fetchData(from url: URL) -&gt; Data? {<br>        // ...<br>    }<br>}<br><br>class DataManager {<br>    let dataFetcher: DataFetching<br><br>    init(dataFetcher: DataFetching) {<br>        self.dataFetcher = dataFetcher<br>    }<br><br>    func getData() -&gt; Data? {<br>        let url = URL(string: &quot;https://example.com/data.json&quot;)!<br>        let data = dataFetcher.fetchData(from: url)<br>        return data<br>    }<br>}<br><br>let dataFetcher = DataFetcher()<br>let dataManager = DataManager(dataFetcher: dataFetcher)<br>let data = dataManager.getData()</pre><p>Now, suppose we have a DataManager class that uses the DataFetcher class to retrieve data.</p><pre>class DataManager {<br>    let dataFetcher = DataFetcher()<br><br>    func getData() -&gt; Data? {<br>        let url = URL(string: &quot;https://example.com/data.json&quot;)!<br>        let data = dataFetcher.fetchData(from: url)<br>        return data<br>    }<br>}</pre><p>This violates the DIP because the DataManager class depends on the DataFetcher class, which is a low-level module.</p><p>To fix this, we can create a new protocol, DataFetching, that the DataFetcher class can conform to.</p><pre>protocol DataFetching {<br>    func fetchData(from url: URL) -&gt; Data?<br>}<br><br>class DataFetcher: DataFetching {<br>    func fetchData(from url: URL) -&gt; Data? {<br>        // ...<br>    }<br>}</pre><p>Now, we can modify the DataManager class to depend on the DataFetching protocol instead of the DataFetcher class.</p><pre>class DataManager {<br>    let dataFetcher: DataFetching<br><br>    init(dataFetcher: DataFetching) {<br>        self.dataFetcher = dataFetcher<br>    }<br><br>    func getData() -&gt; Data? {<br>        let url = URL(string: &quot;https://example.com/data.json&quot;)!<br>        let data = dataFetcher.fetchData(from: url)<br>        return data<br>    }<br>}</pre><p>Now, we can create a new instance of the DataFetcher class and pass it to the DataManager class.</p><pre>let dataFetcher = DataFetcher()<br>let dataManager = DataManager(dataFetcher: dataFetcher)</pre><p>This works because the DataManager class depends on the DataFetching protocol, not on the DataFetcher class.</p><h3>Conclusion</h3><p>In this article, we covered the five SOLID principles and showed you how to implement them in Swift. By following these principles, you can write maintainable, scalable, and testable code that can be easily extended and modified. Remember that these principles are not rules, but rather guidelines, and should be applied based on your specific needs and requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60e4cd5aec6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable iOS Apps with the MVVM-C Design Pattern]]></title>
            <link>https://blog.devgenius.io/building-scalable-ios-apps-with-the-mvvm-c-design-pattern-a6756e3611d1?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6756e3611d1</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 14:16:31 GMT</pubDate>
            <atom:updated>2023-04-05T12:18:00.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*z0W-y-98BTzmECpoKBYK-A@2x.jpeg" /></figure><p>The Model-View-ViewModel-Coordinator (MVVM-C) design pattern is a popular approach to building scalable and maintainable iOS apps. It offers a clear separation of concerns and a structured architecture that makes it easy to test, debug, and modify code. In this article, we will explore how MVVM-C can be used in iOS development.</p><h3>What is MVVM-C?</h3><p>MVVM-C is a design pattern that builds upon the Model-View-ViewModel (MVVM) pattern and adds a Coordinator layer to manage app navigation. In MVVM-C, the app’s navigation flow is handled by a dedicated Coordinator, which is responsible for instantiating and presenting view controllers, passing data between view controllers, and handling user actions.</p><p>The MVVM-C pattern is built around four core components:</p><ul><li>Model: The data model layer represents the app’s data, such as user profiles, product catalogs, or settings.</li><li>View: The view layer displays the app’s user interface and communicates with the view model to update the UI based on the data model.</li><li>View Model: The view model layer acts as an intermediary between the view and the data model. It retrieves data from the data model and transforms it into a format that can be easily displayed by the view.</li><li>Coordinator: The coordinator layer handles the app’s navigation flow. It is responsible for instantiating and presenting view controllers, passing data between view controllers, and handling user actions.</li></ul><h3>Advantages of MVVM-C</h3><p>Using the MVVM-C pattern in iOS development offers several benefits:</p><ul><li>Separation of concerns: MVVM-C clearly separates concerns between the data model, view, view model, and coordinator layers, making it easier to test, debug, and maintain code.</li><li>Scalability: MVVM-C is a scalable architecture that can easily accommodate changes and additions to the app’s functionality. The separation of concerns allows for independent development of each component, making it easier to update and modify code.</li><li>Testability: The MVVM-C pattern allows for easy testing of each component in isolation, ensuring that each layer functions correctly before integrating them into the app.</li><li>Reusability: The MVVM-C pattern allows for the reuse of code across the app, as each component can be used independently of the others.</li></ul><h3>Implementing MVVM-C in iOS Development</h3><p>To implement the MVVM-C pattern in iOS development, follow these steps:</p><ul><li>Define your data model: Define your data model in a separate layer, such as a Swift file or a database.</li></ul><pre>struct User {<br>    let id: Int<br>    let name: String<br>    let email: String<br>}<br><br>class DataManager {<br>    func fetchUser(id: Int, completion: @escaping (User?) -&gt; Void) {<br>        // Fetch user from server or local database<br>    }<br>}<br></pre><ul><li>Implement your view: Implement your view layer using Storyboards or programmatically. Define your view controller and views, and link them to your view model.</li></ul><pre>class UserViewController: UIViewController {<br>    @IBOutlet weak var nameLabel: UILabel!<br>    @IBOutlet weak var emailLabel: UILabel!<br>    <br>    var viewModel: UserViewModel!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        bindViewModel()<br>    }<br>    <br>    func bindViewModel() {<br>        viewModel.user.bind { [weak self] user in<br>            self?.nameLabel.text = user?.name<br>            self?.emailLabel.text = user?.email<br>        }<br>    }<br>}<br></pre><ul><li>Implement your view model: Implement your view model layer using Swift classes or structs. Define your data bindings, business logic, and transformation logic.</li></ul><pre>class UserViewModel {<br>    var user = Observable&lt;User?&gt;(nil)<br>    private let dataManager = DataManager()<br>    <br>    func fetchUser(id: Int) {<br>        dataManager.fetchUser(id: id) { [weak self] user in<br>            self?.user.value = user<br>        }<br>    }<br>}<br></pre><ul><li>Implement your coordinator: Implement your coordinator layer using Swift classes or structs. Define your navigation flow, instantiate and present view controllers, and pass data between them.</li></ul><pre>class AppCoordinator {<br>    let navigationController: UINavigationController<br>    <br>    init(navigationController: UINavigationController) {<br>        self.navigationController = navigationController<br>    }<br>    <br>    func start() {<br>        let userViewController = UserViewController()<br>        let userViewModel = UserViewModel()<br>        userViewController.viewModel = userViewModel<br>        <br>        userViewModel.fetchUser(id: 1)<br>        <br>        navigationController.pushViewController(userViewController, animated: true)<br>    }<br>}<br></pre><ul><li>Integrate your components: Integrate your data model, view, view model, and coordinator layers into your app. Use dependency injection to instantiate each component, and connect them using protocols and delegates.</li></ul><pre>class AppDelegate: UIResponder, UIApplicationDelegate {<br>    var window: UIWindow?<br>    var appCoordinator: AppCoordinator?<br>    <br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        window = UIWindow(frame: UIScreen.main.bounds)<br>        let navigationController = UINavigationController()<br>        window?.rootViewController = navigationController<br>        <br>        appCoordinator = AppCoordinator(navigationController: navigationController)<br></pre><ul><li>Test your app: Test your app by running unit tests and integration tests on each component. Ensure that each layer functions correctly before integrating them into the app.</li></ul><pre>class UserViewModelTests: XCTestCase {<br>    var viewModel: UserViewModel!<br>    <br>    override func setUp() {<br>        viewModel = UserViewModel()<br>    }<br>    <br>    func testFetchUser() {<br>        let expectation = XCTestExpectation(description: &quot;Fetch user&quot;)<br>        <br>        viewModel.user.bind { user in<br>            XCTAssertNotNil(user)<br>            XCTAssertEqual(user?.name, &quot;John Doe&quot;)<br>            XCTAssertEqual(user?.email, &quot;john.doe@example.com&quot;)<br>            expectation.fulfill()<br>        }<br>        <br>        viewModel.fetchUser(id: 1)<br>        <br>        wait(for: [expectation], timeout: 5.0)<br>    }<br>}<br></pre><h3>Conclusion</h3><p>The MVVM-C design pattern is a powerful approach to building scalable and maintainable iOS apps. It offers a clear separation of concerns, scalability, testability, and reusability. By implementing the MVVM-C pattern in your iOS development, you can build apps that are robust, easy to maintain, and can accommodate changes and additions</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6756e3611d1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-scalable-ios-apps-with-the-mvvm-c-design-pattern-a6756e3611d1">Building Scalable iOS Apps with the MVVM-C Design Pattern</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerate Your App Development with Fastlane: A Comprehensive Guide]]></title>
            <link>https://medium.com/@OrfeasUK/accelerate-your-app-development-with-fastlane-a-comprehensive-guide-1dfc57591845?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dfc57591845</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 22:17:23 GMT</pubDate>
            <atom:updated>2023-01-27T22:17:23.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*YPgMj2zxMl5DM-U1gudc_g@2x.jpeg" /></figure><p>Have you ever wanted to speed up your iOS development process and make your app deployment more efficient? If so, you’ve come to the right place. This guide will provide you with a comprehensive overview of Fastlane, a comprehensive powerful toolkit for automating the iOS build and deployment process. We’ll discuss the benefits of using Fastlane, how to install and set it up, and how to leverage Fastlane’s features and integrations to automate iOS deployment and make it easier to manage your app.</p><h3>Introduction to Fastlane</h3><p>Fastlane is a free and open-source toolkit for automating the iOS build and deployment process. It was developed by Felix Krause, a former iOS developer at Dropbox, and is now maintained by a team at Google. Fastlane is designed to help developers save time and reduce the complexity of managing their apps by automating tedious tasks like building, testing, and deploying apps.</p><p>At its core, Fastlane is a command-line tool for automating the iOS build and deployment process. With Fastlane, you can easily create, customize, and execute automated workflows for building, testing, and deploying your apps. You can also use Fastlane’s powerful integrations to automate tasks like creating screenshots and distributing your apps to app stores.</p><h3>Benefits of Using Fastlane</h3><p>Using Fastlane can help you to significantly speed up your iOS development process and reduce the manual labor associated with app deployment. Here are some of the key benefits of using Fastlane:</p><ul><li>Automate tedious tasks like building and testing your apps.</li><li>Create custom workflows for automating app deployment.</li><li>Integrate with other services to automate tasks like creating screenshots and distributing your apps.</li><li>Leverage Fastlane’s powerful integrations to make app deployment easier.</li><li>Easily integrate with continuous integration and delivery (CI/CD) tools.</li><li>Optimize your app development process with automation</li></ul><h3>Installing Fastlane</h3><p>Fastlane is easy to install and use. To get started, you’ll need to download and install the Fastlane command-line tool on your computer. Once you’ve done that, you’ll be ready to set up Fastlane to automate your app deployment process.</p><p>To install Fastlane, you’ll need to open a terminal window and run the following command:</p><pre>$ gem install fastlane</pre><p>This will download and install Fastlane on your computer. You can then verify that Fastlane has been installed correctly by running the following command:</p><pre>$ fastlane  – version</pre><h3>Setting Up Fastlane</h3><p>Once you’ve installed Fastlane, you’ll need to set it up to start automating your iOS development process. The first step is to create a Fastfile, which is a Ruby-based configuration file that tells Fastlane what actions to take and when.</p><p>To create a Fastfile, you’ll need to open a terminal window and run the following command:</p><pre>$ fastlane init</pre><p>This will create a Fastfile in the current directory. You can then use this Fastfile to define and customize your Fastlane workflows.</p><h3>Fastlane Actions and Integrations</h3><p>Fastlane comes with a wide range of actions and integrations that you can use to automate the iOS build and deployment process. These include actions for building, testing, and deploying apps, as well as integrations with other services like App Store Connect and TestFlight.</p><p>Using these actions and integrations, you can automate tasks like creating screenshots, uploading builds to TestFlight, and deploying apps to the App Store. You can also use Fastlane’s powerful integrations to create custom workflows for automating app deployment.</p><h3>Automating iOS Deployment</h3><p>Fastlane makes it easy to automate iOS deployment. With Fastlane, you can create custom workflows for building, testing, and deploying your apps. You can also use Fastlane’s powerful integrations to automate tasks like creating screenshots and distributing your apps to app stores.</p><p>Using Fastlane’s automation capabilities, you can easily set up automated workflows for managing your app’s lifecycle. This can help you to save time and make your app deployment process more efficient.</p><h3>Continuous Integration and Delivery with Fastlane</h3><p>Fastlane is designed to integrate with CI/CD tools like Jenkins, CircleCI, and TravisCI. Using these integrations, you can easily set up automated workflows for building, testing, and deploying your apps.</p><p>These automated workflows can help you to speed up your app development process and make it easier to manage your apps. You can also use these workflows to set up continuous integration and delivery (CI/CD) pipelines for automating the iOS build and deployment process.</p><h3>Tips for Optimizing Fastlane</h3><p>Fastlane is a powerful tool for automating the iOS build and deployment process. Here are some tips for optimizing Fastlane and getting the most out of it:</p><ul><li>Create a custom Fastfile for automating your iOS deployment process.</li><li>Use Fastlane’s powerful integrations to automate tasks like creating screenshots and distributing your apps.</li><li>Leverage Fastlane’s powerful integrations to create custom workflows for automating app deployment.</li><li>Integrate with CI/CD tools like Jenkins, CircleCI, and TravisCI for automating the iOS build and deployment process.</li><li>Optimize your app development process with automation</li></ul><h3>Troubleshooting Fastlane</h3><p>If you encounter any issues while using Fastlane, you can refer to the Fastlane troubleshooting guide. The guide provides detailed instructions and helpful tips for resolving common issues. You can also reach out to the Fastlane community for help and advice.</p><h3>Conclusion</h3><p>In this guide, we’ve discussed how to use Fastlane to accelerate your app development process and make your app deployment more efficient. We’ve discussed the benefits of using Fastlane, how to install and set it up, and how to leverage Fastlane’s features and integrations to automate iOS deployment and make it easier to manage your app.</p><p>Using Fastlane can help you to significantly speed up your app development process and reduce the manual labor associated with app deployment. We hope this guide has given you a better understanding of Fastlane and how to use it to accelerate your iOS development process.</p><p>If you’re looking to accelerate your iOS development process, give Fastlane a try! With Fastlane, you can easily automate the iOS build and deployment process and make your app deployment easier and more efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dfc57591845" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Started with Swift Package Manager: A Comprehensive Guide]]></title>
            <link>https://medium.com/@OrfeasUK/get-started-with-swift-package-manager-a-comprehensive-guide-3276cb7bf71?source=rss-1e4608b513b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3276cb7bf71</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Orfeas Iliopoulos]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 21:43:17 GMT</pubDate>
            <atom:updated>2023-01-24T21:43:17.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Vui148U8usQZq2noaGZF1Q@2x.jpeg" /></figure><p>Swift Package Manager, or SPM, is a tool for managing Swift code and libraries. It’s a great way to quickly and easily get up and running with your project, no matter what type of project you’re working on. In this comprehensive guide, we’ll go over all the basics of Swift Package Manager and how you can get started with it.</p><h3>What is Swift Package Manager?</h3><p>Swift Package Manager is an open-source tool for managing Swift code and libraries. It’s designed to make it easy to share code between different projects and applications. It’s also designed to help you quickly and easily manage dependencies, so you don’t have to worry about keeping track of them manually.</p><p>Swift Package Manager is a great tool for managing libraries, frameworks, and executables. It’s designed to be easy to use and understand. It also makes it easier to keep track of changes, as well as keep your project up-to-date with the latest version of the library or framework you’re using.</p><p>Swift Package Manager is also great for managing dependencies. It helps you keep track of which version of a library you’re using, and helps you find the right version to use in your project. This makes it easy to keep your project up-to-date and make sure you’re always using the right version of a library or framework.</p><h3>Benefits of using Swift Package Manager</h3><p>There are many benefits to using Swift Package Manager. The most obvious benefit is that it makes managing and sharing code between projects much easier. It also makes it much easier to keep track of dependencies, so you don’t have to worry about manually keeping track of them.</p><p>Another benefit of using Swift Package Manager is that it’s designed to be easy to understand and use. This makes it easier to get up and running quickly, and to keep your project up-to-date. Finally, using Swift Package Manager makes it much easier to share your code with others, as it makes it easy to keep track of changes and versions.</p><h3>Components of Swift Package Manager</h3><p>Swift Package Manager is made up of several components. The first component is the Package.swift file, which is the file that contains the package’s metadata. This includes the package name, version, and other information.</p><p>The second component is the Sources folder, which contains the Swift source code for the package. This is where all your code will live.</p><p>The third component is the Tests folder, which contains the unit tests for the package. This is where you’ll write your tests to make sure your package works as expected.</p><p>Finally, the fourth component is the Products folder, which contains the compiled version of the package. This is the version that will be used when you run your project.</p><h3>How to get started with Swift Package Manager</h3><p>Getting started with Swift Package Manager is easy. The first step is to create a new package. To do this, open the Terminal and type in the following command:</p><pre>swift package init</pre><p>This will create a new Xcode project with a Package.swift file. This is where you’ll enter the metadata for your package. You can also add dependencies to your package by adding them to the Package.swift file.</p><p>Once you’ve added your metadata and dependencies, you can build the package. To do this, type in the following command:</p><pre>swift build</pre><p>This will compile your package and create the Products folder. You can then use the package in your project by adding it to the project’s dependencies.</p><h3>Creating your first package</h3><p>Once you’ve created your package and added the necessary metadata, you’re ready to start writing code. The first thing you’ll need to do is create a Sources folder and add your Swift source files to it.</p><p>Once you’ve added your source files, you’ll need to create a Tests folder and add your unit tests to it. This is where you’ll test your package to make sure it works as expected.</p><p>Once you’ve created the Tests folder and added your tests, you’re ready to build the package. To do this, type in the following command:</p><pre>swift build</pre><p>This will compile the package and create the Products folder. You can then use the package in your project by adding it to the project’s dependencies.</p><h3>Working with remote packages</h3><p>If you’re working with a remote package, you’ll need to add it to your project’s dependencies. To do this, open the Package.swift file and add the following line:</p><pre>dependencies: [.package(url: “[PACKAGE_URL]”, from: “[PACKAGE_VERSION]”)]</pre><p>This will add the package to your project’s dependencies. You can then compile the package and use it in your project.</p><p>When you’re working with remote packages, it’s important to keep track of the version you’re using. This will help you make sure you’re always using the right version of the package. You can also use Swift Package Manager to check for updates and keep your project up-to-date.</p><h3>Tips for managing packages with Swift Package Manager</h3><p>When you’re working with Swift Package Manager, there are a few tips to keep in mind. First, make sure to keep your packages up-to-date. This will help you keep your project running smoothly and make sure everything is working as expected.</p><p>Second, make sure to use the right version of a package. This will help you avoid any compatibility issues.</p><p>Third, make sure to keep track of your dependencies. This will help you make sure you’re always using the right version of a library or framework.</p><p>Finally, make sure to use the right tools for managing your packages. Swift Package Manager has a number of tools to help you manage your packages, from creating and building packages to adding dependencies and keeping them up-to-date.</p><h3>Troubleshooting common problems</h3><p>When you’re working with Swift Package Manager, there are a few common problems you might encounter. One common problem is that the package won’t compile. This can be caused by a number of things, including missing dependencies or incorrect code.</p><p>Another common problem is that the package won’t install. This can be caused by a number of things, including incorrect package metadata or incorrect version numbers.</p><p>Finally, another common problem is that the package won’t run. This can be caused by a number of things, including missing dependencies or incorrect code.</p><p>If you encounter any of these problems, there are a few things you can do to troubleshoot them. You can open the Package.swift file and check for any errors in the metadata, or you can check for any missing dependencies. You can also check for any incorrect version numbers, or check for any incorrect code.</p><h3>Swift Package Manager tools and resources</h3><p>There are a number of tools and resources available to help you get started with Swift Package Manager. The first is the official Swift Package Manager website, which has a wealth of information and resources to help you get started.</p><p>The second is the Swift Package Manager repository on GitHub, which has a number of example packages and tools to help you get started.</p><p>Finally, there are a number of third-party tools and resources available to help you get started. These include tutorials, guides, and forums.</p><h3>Conclusion</h3><p>Swift Package Manager is a great tool for managing Swift code and libraries. It’s designed to be easy to use and understand, and makes it easy to keep track of dependencies and keep your project up-to-date. In this comprehensive guide, we’ve gone over all the basics of Swift Package Manager and how you can get started with it. We’ve also gone over some tips for managing packages with Swift Package Manager and troubleshooting common problems. Finally, we’ve gone over some tools and resources to help you get started.</p><p>If you’re looking for a quick and easy way to get up and running with your project, Swift Package Manager is a great choice. With its easy-to-use tools and resources, you’ll be up and running in no time. So, get started with Swift Package Manager today and see how it can make managing your projects easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3276cb7bf71" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>