<?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 Marcelo Henrique on Medium]]></title>
        <description><![CDATA[Stories by Marcelo Henrique on Medium]]></description>
        <link>https://medium.com/@celohenriquech7?source=rss-1e123981185f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q_5lr3yFSjN1zMXZ8Q4OwQ.png</url>
            <title>Stories by Marcelo Henrique on Medium</title>
            <link>https://medium.com/@celohenriquech7?source=rss-1e123981185f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:58:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@celohenriquech7/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[Modularizing the Network Layer in Swift with Combine]]></title>
            <link>https://medium.com/@celohenriquech7/modularizing-the-network-layer-in-swift-with-combine-905c1867b2e6?source=rss-1e123981185f------2</link>
            <guid isPermaLink="false">https://medium.com/p/905c1867b2e6</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Marcelo Henrique]]></dc:creator>
            <pubDate>Tue, 28 May 2024 02:56:25 GMT</pubDate>
            <atom:updated>2024-05-28T03:05:51.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*H-5xzT2fcHiQcSpP.png" /></figure><h3><strong>Introduction</strong></h3><p>In a world where software development is increasingly dynamic, code clarity and maintainability become essential. The network layer, in particular, can become a maze in complex applications. In this article, we will unravel this maze and present a modular approach using Swift and Combine.</p><h3><strong>The Problem</strong></h3><p>Imagine an app that starts with a single network call using URLSession directly in the ViewController. It seems simple, right? But as the app evolves, this simplicity can turn into a monster of duplicated code, coupling, and nearly impossible testing.</p><h3><strong>The Solution: Modular Network Layer</strong></h3><h4><strong>APIRequest and HTTPMethod</strong></h4><p>Before delving into network calls, it’s crucial to establish a solid foundation. This foundation is the structure of our requests.</p><pre>import Foundation<br><br>public protocol APIRequest {<br>    associatedtype ResponseType: Decodable<br>    var baseURL: URL { get }<br>    var path: String { get }<br>    var method: HTTPMethod { get }<br>    var body: Data? { get }<br>    var customHeaderFields: [String: String]? { get }<br>}<br><br>public extension APIRequest {<br>    var url: URL? {<br>        return baseURL.appendingPathComponent(path)<br>    }<br>}<br><br>public enum HTTPMethod: String {<br>    case get = &quot;GET&quot;<br>    case post = &quot;POST&quot;<br>    case patch = &quot;PATCH&quot;<br>    case delete = &quot;DELETE&quot;<br>}</pre><p>Here, APIRequest serves as a contract that all our requests will follow, while HTTPMethod enumerates the HTTPMethod we can use.</p><h4><strong>NetworkSession and URLSession</strong></h4><p>With the foundation established, it’s time to think about how we will load our data. Creating an abstraction here not only makes testing easier but also lays the groundwork for future extensions.</p><pre>public protocol NetworkSession: AnyObject {<br>    func loadData(from url: URLRequest, completionHandler: @escaping (Result&lt;(Data, URLResponse), Error&gt;) -&gt; Void)<br>}<br><br>extension URLSession: NetworkSession {<br>    public func loadData(from url: URLRequest, completionHandler: @escaping (Result&lt;(Data, URLResponse), Error&gt;) -&gt; Void) {<br>        let task = dataTask(with: url, completionHandler: { data, response, error in<br>            if let data = data, let response = response {<br>                completionHandler(.success((data, response)))<br>            } else if let error = error {<br>                completionHandler(.failure(error))<br>            }<br>        })<br>        task.resume()<br>    }<br>}</pre><h4><strong>APIServiceManager, ResponseDecoder, and APIError</strong></h4><p>Now, we enter the heart of our network layer. But before diving into the code, let’s understand Combine’s role here. Combine is a framework that allows us to work with asynchronous operations and events using functional types, making our code cleaner and more understandable.</p><p>APIError helps us deal with the inevitable errors we will encounter. ResponseDecoder, on the other hand, is an abstraction that allows us to decode responses in any way we want. Finally, DefaultAPIServiceManager is where the magic happens, integrating everything and using Combine to handle asynchronous operations.</p><pre>import Foundation<br>import Combine<br><br>public enum APIError: Error {<br>    case invalidURL<br>    case apiError(cause: Error, statusCode: Int?)<br>    case invalidResponse<br>    case notFound<br>    case serverError<br>    case decodingError(Error)<br>}<br><br>public protocol APIServiceManager {<br>    func fetch&lt;T: APIRequest&gt;(request: T) -&gt; AnyPublisher&lt;T.ResponseType, APIError&gt;<br>}<br><br>public protocol ResponseDecoder {<br>    func decode&lt;T: Decodable&gt;(_ type: T.Type, from data: Data) throws -&gt; T<br>}<br><br>public struct DefaultResponseDecoder: ResponseDecoder {<br>    public init() {}<br><br>    public func decode&lt;T: Decodable&gt;(_ type: T.Type, from data: Data) throws -&gt; T {<br>        let decoder = JSONDecoder()<br>        return try decoder.decode(type, from: data)<br>    }<br>}<br><br>public class DefaultAPIServiceManager: APIServiceManager {<br>    private let session: NetworkSession<br>    private let decoder: ResponseDecoder<br>    <br>    public init(session: NetworkSession, decoder: ResponseDecoder = DefaultResponseDecoder()) {<br>        self.session = session<br>        self.decoder = decoder<br>    }<br>    <br>    public convenience init() {<br>        self.init(session: URLSession.shared, decoder: DefaultResponseDecoder())<br>    }<br>    <br>    public func fetch&lt;T: APIRequest&gt;(request: T) -&gt; AnyPublisher&lt;T.ResponseType, APIError&gt; {<br>        return Future { [weak self] promise in<br>            self?.performRequest(request: request, completion: { result in<br>                switch result {<br>                case .success(let model):<br>                    promise(.success(model))<br>                case .failure(let error):<br>                    promise(.failure(error))<br>                }<br>            })<br>        }<br>        .eraseToAnyPublisher()<br>    }<br>    <br>    private func performRequest&lt;T: APIRequest&gt;(request: T, completion: @escaping (Result&lt;T.ResponseType, APIError&gt;) -&gt; Void) {<br>        guard let url = request.url else {<br>            return completion(.failure(.invalidURL))<br>        }<br>        <br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = request.method.rawValue<br>        urlRequest.allHTTPHeaderFields = request.customHeaderFields<br>        urlRequest.httpBody = request.body<br>        <br>        session.loadData(from: urlRequest) { result in<br>            switch result {<br>            case .success(let (data, response)):<br>                self.handleResponse(response, data, nil, request: request, completion: completion)<br>            case .failure(let error):<br>                self.handleResponse(nil, nil, error, request: request, completion: completion)<br>            }<br>        }<br>    }<br>    <br>    private func handleResponse&lt;T: APIRequest&gt;(_ response: URLResponse?, _ data: Data?, _ error: Error?, request: T, completion: @escaping (Result&lt;T.ResponseType, APIError&gt;) -&gt; Void) {<br>        if let error = error {<br>            completion(.failure(.apiError(cause: error, statusCode: nil)))<br>            return<br>        }<br>        <br>        guard let httpResponse = response as? HTTPURLResponse else {<br>            completion(.failure(.invalidResponse))<br>            return<br>        }<br>        <br>        switch httpResponse.statusCode {<br>        case 200..&lt;300:<br>            // Success range<br>            break<br>        case 404:<br>            completion(.failure(.notFound))<br>            return<br>        case 500..&lt;600:<br>            completion(.failure(.serverError))<br>            return<br>        default:<br>            completion(.failure(.apiError(cause: NSError(domain: &quot;unknownError&quot;, code: httpResponse.statusCode, userInfo: nil), statusCode: httpResponse.statusCode)))<br>            return<br>        }<br>        <br>        guard let data = data else {<br>            completion(.failure(.invalidResponse))<br>            return<br>        }<br>        <br>        do {<br>            let model = try self.decoder.decode(T.ResponseType.self, from: data)<br>            completion(.success(model))<br>        } catch {<br>            completion(.failure(.decodingError(error)))<br>        }<br>    }<br>}</pre><h4><strong>Practical Example: Using the CoinGecko API</strong></h4><p>To demonstrate our network layer in action, let’s use the CoinGecko API, a popular platform that provides information about cryptocurrencies. We will focus on obtaining a list of available coins.</p><h4><strong>Coin Structure</strong></h4><p>First, let’s define the structure of a coin we expect to receive from the API:</p><pre>struct Coin: Decodable {<br>    let id: String<br>    let symbol: String<br>    let name: String<br>}</pre><h4><strong>Coin List Request</strong></h4><p>Now, let’s create a specific request to get the list of coins:</p><pre>struct CoinListRequest: APIRequest {<br>    typealias ResponseType = [Coin]<br>    <br>    var baseURL: URL {<br>        return URL(string: &quot;https://api.coingecko.com&quot;)!<br>    }<br>    <br>    var path: String {<br>        return &quot;/api/v3/coins/list&quot;<br>    }<br>    <br>    var method: HTTPMethod {<br>        return .get<br>    }<br>    <br>    var body: Data? {<br>        return nil<br>    }<br>    <br>    var customHeaderFields: [String : String]? {<br>        return nil<br>    }<br>}</pre><p>You may have noticed that we are returning nil for body and customHeaderFields. This is because, for this specific example, we don’t need to send a request body or custom header fields. However, in a real scenario, these fields can be crucial.</p><p>For example, if we were making a POST call to create a new coin, the request body could contain the details of that coin:</p><pre>var body: Data? {<br>    let coinDetails = [<br>        &quot;id&quot;: &quot;newcoin&quot;,<br>        &quot;symbol&quot;: &quot;nc&quot;,<br>        &quot;name&quot;: &quot;New Coin&quot;<br>    ]<br>    return try? JSONSerialization.data(withJSONObject: coinDetails, options: [])<br>}</pre><p>And if the API required authentication, the custom header fields could contain an authentication token:</p><pre>var customHeaderFields: [String : String]? {<br>    return [&quot;Authorization&quot;: &quot;Bearer YOUR_TOKEN_HERE&quot;]<br>}</pre><p>These are just simple examples, but they illustrate how flexible and adaptable the APIRequest structure is to different network call needs.</p><h4><strong>Testability with CoreNetworkTests</strong></h4><p>What is code without tests? Incomplete. Thanks to our modular approach, writing unit tests becomes much simpler. Let’s use the above structures to perform tests on our network layer.</p><pre>import XCTest<br>import Combine<br>@testable import CoreNetwork<br><br>final class CoreNetworkTests: XCTestCase {<br>    <br>    var cancellables: Set&lt;AnyCancellable&gt; = []<br>    <br>    func testCoinListAPI() throws {<br>        let expectation = self.expectation(description: &quot;Fetching coin list&quot;)<br>        <br>        let apiManager = DefaultAPIServiceManager()<br>        let request = CoinListRequest()<br>        <br>        apiManager.fetch(request: request)<br>            .sink(receiveCompletion: { completion in<br>                switch completion {<br>                case .finished:<br>                    break<br>                case .failure(leterror):<br>                    XCTFail(&quot;API call failed with error: (error)&quot;)<br>                }<br>            }, receiveValue: { coins in<br>                XCTAssert(!coins.isEmpty, &quot;Coin list is empty&quot;)<br>                expectation.fulfill()<br>            })<br>            .store(in: &amp;cancellables)<br>        waitForExpectations(timeout: 10, handler: nil)<br>    }<br>}</pre><h4><strong>Conclusion</strong></h4><p>Modularization, as we have seen, is not just a technique to organize code. It is a strategy that, when correctly implemented, can bring numerous benefits to software development. In large teams, modularization facilitates collaboration, allowing different developers to work on distinct parts of the code without interfering with each other. Furthermore, modular code is more sustainable in the long run. It is easier to maintain, test, and scale. With Swift and Combine as allies, we have a solid and powerful foundation on which an application can grow and evolve, confidently and effectively tackling the challenges of modern development.</p><h4><strong>Links and References</strong></h4><p>While this article was written based on experiences and best practices, it is always helpful to consult official documentation and other resources to delve deeper into the topic. Here are some links I used and that may be useful:</p><p>- <a href="https://swift.org/documentation/">Official Swift Documentation</a><br>- <a href="https://developer.apple.com/documentation/combine">Combine Framework</a><br>- <a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a></p><h4><strong>Now it’s your turn!</strong></h4><p>I encourage you to test this approach in your own app. How are you implementing this modular network layer? Is there anything you think we could improve or optimize? I would love to hear your comments and feedback. The community benefits greatly when we share our experiences and learnings. So, try it out, adapt it to your needs, and share your discoveries!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=905c1867b2e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modularizando a camada de rede em Swift com Combine]]></title>
            <link>https://medium.com/@celohenriquech7/modularizando-a-camada-de-rede-em-swift-com-combine-195705bd3530?source=rss-1e123981185f------2</link>
            <guid isPermaLink="false">https://medium.com/p/195705bd3530</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Marcelo Henrique]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 17:19:02 GMT</pubDate>
            <atom:updated>2023-10-03T20:13:42.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UROscLEA73-cI0-kJXTRBA.png" /></figure><h3>Introdução</h3><p>Em um mundo onde o desenvolvimento de software é cada vez mais dinâmico, a clareza e a manutenção do código tornam-se essenciais. A camada de rede, em particular, pode se tornar um labirinto em aplicações complexas. Neste artigo, vamos desvendar esse labirinto e apresentar uma abordagem modular usando Swift e Combine.</p><h3>O Problema</h3><p>Imagine um aplicativo que começa com uma única chamada de rede usando URLSession diretamente no ViewController. Parece simples, certo? Mas à medida que o aplicativo evolui, essa simplicidade pode se transformar em um monstro de código duplicado, acoplamento e testes quase impossíveis.</p><h3>A Solução: Camada de Rede Modular</h3><h4>APIRequest e HTTPMethod</h4><p>Antes de nos aprofundarmos nas chamadas de rede, é fundamental estabelecer uma base sólida. E essa base é a estrutura de nossas solicitações.</p><pre>import Foundation<br><br>public protocol APIRequest {<br>    associatedtype ResponseType: Decodable<br>    var baseURL: URL { get }<br>    var path: String { get }<br>    var method: HTTPMethod { get }<br>    var body: Data? { get }<br>    var customHeaderFields: [String: String]? { get }<br>}<br><br>public extension APIRequest {<br>    var url: URL? {<br>        return baseURL.appendingPathComponent(path)<br>    }<br>}<br><br>public enum HTTPMethod: String {<br>    case get = &quot;GET&quot;<br>    case post = &quot;POST&quot;<br>    case patch = &quot;PATCH&quot;<br>    case delete = &quot;DELETE&quot;<br>}</pre><p>Aqui, APIRequest serve como um contrato que todas as nossas solicitações seguirão, enquanto HTTPMethod enumera os métodos HTTP que podemos usar.</p><h4>NetworkSession e URLSession</h4><p>Com a base estabelecida, é hora de pensar em como carregaremos nossos dados. Criar uma abstração aqui nos permite não apenas facilitar os testes, mas também preparar o terreno para extensões futuras.</p><pre>public protocol NetworkSession: AnyObject {<br>    func loadData(from url: URLRequest, completionHandler: @escaping (Result&lt;(Data, URLResponse), Error&gt;) -&gt; Void)<br>}<br><br>extension URLSession: NetworkSession {<br>    public func loadData(from url: URLRequest, completionHandler: @escaping (Result&lt;(Data, URLResponse), Error&gt;) -&gt; Void) {<br>        let task = dataTask(with: url, completionHandler: { data, response, error in<br>            if let data = data, let response = response {<br>                completionHandler(.success((data, response)))<br>            } else if let error = error {<br>                completionHandler(.failure(error))<br>            }<br>        })<br>        task.resume()<br>    }<br>}</pre><h4>APIServiceManager, ResponseDecoder e APIError</h4><p>Agora, entramos no coração da nossa camada de rede. Mas, antes de mergulharmos no código, vamos entender o papel do Combine aqui. Combine é uma framework que nos permite trabalhar com operações assíncronas e eventos usando tipos funcionais, tornando nosso código mais limpo e compreensível.</p><p>APIError nos ajuda a lidar com os inevitáveis erros que encontraremos. ResponseDecoder, por outro lado, é uma abstração que nos permite decodificar respostas da maneira que quisermos. E finalmente, DefaultAPIServiceManager é onde a mágica acontece, integrando tudo e usando Combine para lidar com as operações assíncronas.</p><pre>import Foundation<br>import Combine<br><br>public enum APIError: Error {<br>    case invalidURL<br>    case apiError(cause: Error, statusCode: Int?)<br>    case invalidResponse<br>    case notFound<br>    case serverError<br>    case decodingError(Error)<br>}<br><br>public protocol APIServiceManager {<br>    func fetch&lt;T: APIRequest&gt;(request: T) -&gt; AnyPublisher&lt;T.ResponseType, APIError&gt;<br>}<br><br>public protocol ResponseDecoder {<br>    func decode&lt;T: Decodable&gt;(_ type: T.Type, from data: Data) throws -&gt; T<br>}<br><br>public struct DefaultResponseDecoder: ResponseDecoder {<br>    public init() {}<br><br>    public func decode&lt;T: Decodable&gt;(_ type: T.Type, from data: Data) throws -&gt; T {<br>        let decoder = JSONDecoder()<br>        return try decoder.decode(type, from: data)<br>    }<br>}<br><br>public class DefaultAPIServiceManager: APIServiceManager {<br>    private let session: NetworkSession<br>    private let decoder: ResponseDecoder<br>    <br>    public init(session: NetworkSession, decoder: ResponseDecoder = DefaultResponseDecoder()) {<br>        self.session = session<br>        self.decoder = decoder<br>    }<br>    <br>    public convenience init() {<br>        self.init(session: URLSession.shared, decoder: DefaultResponseDecoder())<br>    }<br>    <br>    public func fetch&lt;T: APIRequest&gt;(request: T) -&gt; AnyPublisher&lt;T.ResponseType, APIError&gt; {<br>        return Future { [weak self] promise in<br>            self?.performRequest(request: request, completion: { result in<br>                switch result {<br>                case .success(let model):<br>                    promise(.success(model))<br>                case .failure(let error):<br>                    promise(.failure(error))<br>                }<br>            })<br>        }<br>        .eraseToAnyPublisher()<br>    }<br>    <br>    private func performRequest&lt;T: APIRequest&gt;(request: T, completion: @escaping (Result&lt;T.ResponseType, APIError&gt;) -&gt; Void) {<br>        guard let url = request.url else {<br>            return completion(.failure(.invalidURL))<br>        }<br>        <br>        var urlRequest = URLRequest(url: url)<br>        urlRequest.httpMethod = request.method.rawValue<br>        urlRequest.allHTTPHeaderFields = request.customHeaderFields<br>        urlRequest.httpBody = request.body<br>        <br>        session.loadData(from: urlRequest) { result in<br>            switch result {<br>            case .success(let (data, response)):<br>                self.handleResponse(response, data, nil, request: request, completion: completion)<br>            case .failure(let error):<br>                self.handleResponse(nil, nil, error, request: request, completion: completion)<br>            }<br>        }<br>    }<br>    <br>    private func handleResponse&lt;T: APIRequest&gt;(_ response: URLResponse?, _ data: Data?, _ error: Error?, request: T, completion: @escaping (Result&lt;T.ResponseType, APIError&gt;) -&gt; Void) {<br>        if let error = error {<br>            completion(.failure(.apiError(cause: error, statusCode: nil)))<br>            return<br>        }<br>        <br>        guard let httpResponse = response as? HTTPURLResponse else {<br>            completion(.failure(.invalidResponse))<br>            return<br>        }<br>        <br>        switch httpResponse.statusCode {<br>        case 200..&lt;300:<br>            // Success range<br>            break<br>        case 404:<br>            completion(.failure(.notFound))<br>            return<br>        case 500..&lt;600:<br>            completion(.failure(.serverError))<br>            return<br>        default:<br>            completion(.failure(.apiError(cause: NSError(domain: &quot;unknownError&quot;, code: httpResponse.statusCode, userInfo: nil), statusCode: httpResponse.statusCode)))<br>            return<br>        }<br>        <br>        guard let data = data else {<br>            completion(.failure(.invalidResponse))<br>            return<br>        }<br>        <br>        do {<br>            let model = try self.decoder.decode(T.ResponseType.self, from: data)<br>            completion(.success(model))<br>        } catch {<br>            completion(.failure(.decodingError(error)))<br>        }<br>    }<br>}</pre><h3>Exemplo Prático: Utilizando a API do CoinGecko</h3><p>Para demonstrar nossa camada de rede em ação, vamos utilizar a API do CoinGecko, uma plataforma popular que fornece informações sobre criptomoedas. Vamos focar em obter uma lista de moedas disponíveis.</p><p><strong>Estrutura da Moeda (Coin)</strong></p><p>Primeiro, vamos definir a estrutura de uma moeda que esperamos receber da API:</p><pre>struct Coin: Decodable {<br>    let id: String<br>    let symbol: String<br>    let name: String<br>}</pre><p><strong>Solicitação da Lista de Moedas (CoinListRequest)</strong></p><p>Agora, vamos criar uma solicitação específica para obter a lista de moedas:</p><pre>struct CoinListRequest: APIRequest {<br>    typealias ResponseType = [Coin]<br>    <br>    var baseURL: URL {<br>        return URL(string: &quot;https://api.coingecko.com&quot;)!<br>    }<br>    <br>    var path: String {<br>        return &quot;/api/v3/coins/list&quot;<br>    }<br>    <br>    var method: HTTPMethod {<br>        return .get<br>    }<br>    <br>    var body: Data? {<br>        return nil<br>    }<br>    <br>    var customHeaderFields: [String : String]? {<br>        return nil<br>    }<br>}</pre><p>Você deve ter notado que estamos retornando nil para body e customHeaderFields. Isso é porque, para este exemplo específico, não precisamos enviar um corpo de solicitação ou campos de cabeçalho personalizados. No entanto, em um cenário real, esses campos podem ser cruciais.</p><p>Por exemplo, se estivéssemos fazendo uma chamada POST para criar uma nova moeda, o corpo da solicitação poderia conter os detalhes dessa moeda:</p><pre>var body: Data? {<br>    let coinDetails = [<br>        &quot;id&quot;: &quot;newcoin&quot;,<br>        &quot;symbol&quot;: &quot;nc&quot;,<br>        &quot;name&quot;: &quot;New Coin&quot;<br>    ]<br>    return try? JSONSerialization.data(withJSONObject: coinDetails, options: [])<br>}</pre><p>E, se a API exigisse autenticação, os campos de cabeçalho personalizados poderiam conter um token de autenticação:</p><pre>var customHeaderFields: [String : String]? {<br>    return [&quot;Authorization&quot;: &quot;Bearer YOUR_TOKEN_HERE&quot;]<br>}</pre><p>Estes são apenas exemplos simples, mas ilustram como a estrutura APIRequest é flexível e adaptável a diferentes necessidades de chamadas de rede.</p><h3>Testabilidade com CoreNetworkTests</h3><p>O que é um código sem testes? Incompleto. Graças à nossa abordagem modular, escrever testes unitários torna-se muito mais simples. Vamos utilizar as estruturas acima para realizar o teste da nossa camada de rede.</p><pre>import XCTest<br>import Combine<br>@testable import CoreNetwork<br><br>final class CoreNetworkTests: XCTestCase {<br>    <br>    var cancellables: Set&lt;AnyCancellable&gt; = []<br><br>    func testCoinListAPI() throws {<br>        let expectation = self.expectation(description: &quot;Fetching coin list&quot;)<br>        <br>        let apiManager = DefaultAPIServiceManager()<br>        let request = CoinListRequest()<br>        <br>        apiManager.fetch(request: request)<br>            .sink(receiveCompletion: { completion in<br>                switch completion {<br>                case .finished:<br>                    break<br>                case .failure(let error):<br>                    XCTFail(&quot;API call failed with error: \(error)&quot;)<br>                }<br>            }, receiveValue: { coins in<br>                XCTAssert(!coins.isEmpty, &quot;Coin list is empty&quot;)<br>                expectation.fulfill()<br>            })<br>            .store(in: &amp;cancellables)<br>        <br>        waitForExpectations(timeout: 10, handler: nil)<br>    }<br><br>}</pre><h3>Conclusão</h3><p>A modularização, como vimos, não é apenas uma técnica para organizar o código. Ela é uma estratégia que, quando implementada corretamente, pode trazer inúmeros benefícios para o desenvolvimento de software. Em equipes grandes, a modularização facilita a colaboração, pois permite que diferentes desenvolvedores trabalhem em partes distintas do código sem interferir uns nos outros. Além disso, um código modular é mais sustentável a longo prazo. Ele é mais fácil de ser mantido, testado e escalado. Com o Swift e o Combine como aliados, temos uma base sólida e poderosa sobre a qual um aplicativo pode crescer e evoluir, enfrentando os desafios do desenvolvimento moderno com confiança e eficácia.</p><h3><strong>Links e Referências</strong></h3><p>Embora este artigo tenha sido escrito com base em experiências e práticas recomendadas, é sempre útil consultar a documentação oficial e outros recursos para se aprofundar ainda mais no tópico. Aqui estão alguns links que utilizei e podem ser úteis:</p><ul><li><a href="https://swift.org/documentation/">Documentação oficial do Swift</a></li><li><a href="https://developer.apple.com/documentation/combine">Combine Framework</a></li><li><a href="https://developer.apple.com/documentation/foundation/urlsession">URLSession</a></li></ul><h3>Agora é sua vez!</h3><p>Encorajo você a testar essa abordagem em seu próprio aplicativo. Como você está implementando essa camada de rede modular? Há algo que você acha que poderíamos melhorar ou otimizar? Adoraria ouvir seus comentários e feedback. A comunidade se beneficia enormemente quando compartilhamos nossas experiências e aprendizados. Então, experimente, adapte às suas necessidades e compartilhe suas descobertas!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195705bd3530" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>