<?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 Mohammad Razipour on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Razipour on Medium]]></description>
        <link>https://medium.com/@razipour1993?source=rss-654f2d06d65f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zPxfk1jbGG_0rnufNON-ww@2x.jpeg</url>
            <title>Stories by Mohammad Razipour on Medium</title>
            <link>https://medium.com/@razipour1993?source=rss-654f2d06d65f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 14:34:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@razipour1993/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[Who Actually Calls the Reducer in React?]]></title>
            <link>https://medium.com/@razipour1993/who-actually-calls-the-reducer-in-react-685b8f91ea8a?source=rss-654f2d06d65f------2</link>
            <guid isPermaLink="false">https://medium.com/p/685b8f91ea8a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[state]]></category>
            <dc:creator><![CDATA[Mohammad Razipour]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 14:36:09 GMT</pubDate>
            <atom:updated>2026-04-24T14:36:09.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Clear and Practical Look at How useReducer Really Works</h3><p>One of the most common questions developers encounter when learning React’s useReducer hook is:</p><p>**“When I call dispatch, who actually runs the reducer?</p><p>Do <em>I</em> execute it, or does React handle that internally?”**</p><p>This question sounds simple, but the answer opens the door to understanding how React’s state system actually works under the hood.</p><p>Let’s break it down clearly and practically.</p><h3>What Happens the Moment You Call dispatch?</h3><p>Whenever you write:</p><pre>dispatch({ type: &quot;increment&quot; })</pre><p><strong>you are NOT calling the reducer yourself.</strong></p><p>And even more importantly:</p><ul><li>dispatch does <strong>not</strong> directly execute the reducer either.</li></ul><p>Instead, this is what happens:</p><ol><li>React queues your action.</li><li>React marks your component to be re-rendered soon.</li><li>During the next render cycle, React processes all queued actions.</li><li>Only at that moment, React calls the reducer:</li></ol><pre>reducer(currentState, action)</pre><ol><li>React stores the reducer’s return value as the new state.</li><li>React re-renders your component.</li></ol><p>So the short, definitive answer:</p><h3>React is the one that calls your reducer — not you.</h3><h3>Why Doesn’t React Let You Call the Reducer Directly?</h3><p>If React allowed you to execute reducers manually:</p><ul><li>state would fall out of React’s control</li><li>batching updates would break</li><li>re-renders would become unpredictable</li><li>concurrency and scheduling wouldn’t work</li><li>UI stability would collapse</li></ul><p>React intentionally forces all state updates to flow through <strong>one controlled pathway</strong>:</p><pre>dispatch → reducer → new state → re-render</pre><p>This ensures consistency, predictability, and rendering efficiency.</p><h3>What Does dispatch Actually Do?</h3><p>Conceptually, dispatch performs three tasks:</p><h3>1. It queues the action</h3><p>React records the action and adds it to its internal update queue.</p><h3>2. It schedules a re-render</h3><p>React marks the component as needing to re-render soon.</p><h3>3. It lets React decide when to run the reducer</h3><p>React executes the reducer <em>during the render phase</em>, not immediately.</p><p>This is why logging state right after dispatch never shows the updated value — the reducer hasn’t run yet.</p><h3>So What Is the Reducer, Really?</h3><p>A reducer is a <strong>pure function</strong>:</p><pre>function reducer(state, action) {<br>  switch (action.type) {<br>    case &quot;increment&quot;:<br>      return { ...state, count: state.count + 1 }<br>    default:<br>      return state<br>  }<br>}</pre><p>Because reducers are pure:</p><ul><li>no timing</li><li>no side effects</li><li>predictable output</li></ul><p>React can safely call them whenever it needs to — even multiple times — to compute new UI.</p><p>This design is the foundation of how React supports concurrent rendering, batching, and predictable state management.</p><h3>Why Understanding This Matters</h3><p>Knowing <strong>who</strong> calls the reducer helps you understand several confusing behaviors:</p><h3>1. State updates aren’t immediate</h3><p>React waits until the render phase to execute reducers.</p><h3>2. Multiple dispatches may produce one render</h3><p>Because React batches them.</p><h3>3. Logs after dispatch show old values</h3><p>Because the reducer hasn’t run yet.</p><h3>4. State is always consistent and predictable</h3><p>React centrally controls when updates happen.</p><h3>A Helpful Mental Model</h3><p>Think of useReducer as a three-step pipeline:</p><pre>[ dispatch ] → [ action queue ] → [ React runs reducer ]</pre><p>Your job ends at the first step.</p><p>React takes care of the rest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685b8f91ea8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Does “Next Render” Mean in React?]]></title>
            <link>https://medium.com/@razipour1993/what-does-next-render-mean-in-react-3a252b21d265?source=rss-654f2d06d65f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a252b21d265</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Mohammad Razipour]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 12:54:25 GMT</pubDate>
            <atom:updated>2026-04-24T12:56:02.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>And Why Doesn’t State Update Immediately?</h3><p>If you’ve worked with React for a while, you’ve probably encountered something like this:</p><pre>setLoading(false);<br>console.log(loading);</pre><p>You expected false to be logged.</p><p>Instead, you saw the previous value: true.</p><p>At first glance, this feels strange.</p><p>Didn’t we just update the state?</p><p>Why isn’t it reflected immediately?</p><p>To understand this behavior, we need to clearly understand what “the next render” means in React.</p><h3>What Does “Render” Mean in React?</h3><p>In React, components are essentially functions that return JSX:</p><pre>function App() {<br>  return &lt;div&gt;{name}&lt;/div&gt;;<br>}</pre><p>Whenever state or props change, React re-executes this function to produce updated UI.</p><p>This re-execution is called a <strong>render</strong>.</p><p>Rendering simply means running your component again to produce the next UI output.</p><h3>When Does the “Next Render” Happen?</h3><p>When you call setState, React does <strong>not</strong> update the state immediately.</p><p>Instead, it:</p><ol><li>Queues the state update</li><li>Batches multiple updates together</li><li>Triggers a new render afterward</li></ol><p>That new execution of the component is what we call <strong>the next render</strong>.</p><p>The key point is:</p><blockquote><em>setState schedules an update — it does not apply it instantly.</em></blockquote><h3>A Practical Example</h3><p>Assume our initial state looks like this:</p><pre>const [loading, setLoading] = useState(true);<br>const [name, setName] = useState&lt;string | undefined&gt;(undefined);</pre><p>And we have this effect:</p><pre>useEffect(() =&gt; {<br>  getPerson().then((person) =&gt; {<br>    setLoading(false);<br>    setName(person.name);<br>    console.log(&quot;State values:&quot;, loading, name);<br>  });<br>}, []);</pre><p>If person.name is &quot;Bob&quot;, you might expect:</p><pre>State values: false Bob</pre><p>But instead, you’ll see:</p><pre>State values: true undefined</pre><p>Why?</p><p>Because at the moment console.log runs, the <strong>next render hasn’t happened yet</strong>.</p><p>React has only queued the updates — it hasn’t applied them.</p><h3>Execution Timeline (Step-by-Step)</h3><h3>1. Initial Render</h3><pre>loading = true<br>name = undefined</pre><p>React renders the component.</p><h3>2. useEffect Runs</h3><p>The Promise (getPerson()) is called.</p><h3>3. Promise Resolves</h3><p>Inside .then():</p><pre>setLoading(false);<br>setName(&quot;Bob&quot;);</pre><p>React queues these updates.</p><h3>4. console.log Executes</h3><p>The next render has not happened yet, so the values are still:</p><pre>loading = true<br>name = undefined</pre><h3>5. Next Render Happens</h3><p>React re-executes the component with the updated state:</p><pre>loading = false<br>name = &quot;Bob&quot;</pre><p>The UI updates accordingly.</p><h3>Why Does React Do This?</h3><p>If React applied every state update immediately:</p><ul><li>Each update would trigger its own render</li><li>Several setState calls would cause multiple renders</li><li>Performance would suffer</li></ul><p>Instead, React batches updates:</p><pre>3 setState calls  <br>↓  <br>1 render</pre><p>This approach makes React applications more efficient and predictable.</p><h3>The Role of JavaScript Closures</h3><p>There’s another key detail: JavaScript closures.</p><p>When useEffect runs, it captures the state values from that specific render.</p><p>This means the console.log inside the effect is still referencing the <strong>old</strong> values — even though state updates have been scheduled.</p><p>This is normal JavaScript behavior and not a React bug.</p><h3>How to Access the Updated State</h3><p>If you want to use the updated state values, listen for them in a separate effect:</p><pre>useEffect(() =&gt; {<br>  console.log(&quot;Updated values:&quot;, loading, name);<br>}, [loading, name]);</pre><p>This effect runs <strong>after</strong> a render where loading or name has changed, so it always logs the newest state.</p><h3>Final Thoughts</h3><ul><li>setState does not update state immediately</li><li>React queues updates and applies them in the next render</li><li>The component re-executes with updated state</li><li>Updated values are only available <strong>in or after</strong> that next render</li><li>Understanding this cycle makes React behavior predictable and clearer</li></ul><p>Once you fully grasp this rendering model, many confusing moments in React start to make perfect sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a252b21d265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolving Role of iOS Developers: Not Obsolete, But Transformed]]></title>
            <link>https://medium.com/@razipour1993/the-evolving-role-of-ios-developers-not-obsolete-but-transformed-223d49e77fe3?source=rss-654f2d06d65f------2</link>
            <guid isPermaLink="false">https://medium.com/p/223d49e77fe3</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[future-of-work]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohammad Razipour]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 04:44:12 GMT</pubDate>
            <atom:updated>2025-07-09T04:44:12.807Z</atom:updated>
            <content:encoded><![CDATA[<p>The landscape of iOS development has been rapidly changing. With the advent of <strong>Swift</strong>, the introduction of <strong>SwiftUI</strong>, and now the powerful rise of <strong>Artificial Intelligence</strong>, iOS developers find themselves at a pivotal moment. Are we approaching the end of traditional programming as we know it? Will iOS developers become obsolete, or will their roles and skill sets simply evolve?</p><p>In this article, I’ll explore four key areas that will shape the future of iOS development careers:</p><h3>1. The Programming Language: How Far Will Swift Go?</h3><p><strong>Swift</strong> has largely replaced Objective-C, and Apple continues to invest heavily in its enhancement. From Concurrency to SwiftData and macros, we’re seeing continuous expansion of the language.</p><p><strong>Will Apple introduce a new language?</strong></p><p>It’s highly unlikely. Apple has spent over a decade building the Swift ecosystem and gaining a large community of developers. Instead of a new language, the future will likely involve <strong>intelligent evolution of Swift</strong> — perhaps adding AI-aware capabilities or even better WebAssembly support.</p><h3>2. Frameworks and Tools: SwiftUI vs. UIKit</h3><p><strong>SwiftUI</strong> brought a significant revolution to UI design for Apple apps, but UIKit is still widely used in many complex applications.</p><p><strong>Will UIKit disappear?</strong></p><p>No. <strong>UIKit</strong> will become a <strong>low-level tool</strong> for specific use cases. <strong>SwiftUI</strong> will be the primary choice for 90% of common development scenarios — especially with <strong>visionOS</strong> being built entirely on SwiftUI.</p><p>The result? Future developers will need to be skilled in <strong>combining SwiftUI and UIKit</strong>. Leveraging UIViewRepresentable or UIHostingController will become a true art form.</p><h3>3. Cross-Platform Development: Unification or Adaptation?</h3><p>With the growth of visionOS, watchOS, and macOS, the question arises: can we “write once, run everywhere”?</p><p><strong>The realistic answer?</strong></p><p>Not exactly. Instead, a better approach will be: <strong>“Architect Once, Adapt Everywhere”</strong></p><p>This means that the core logic of your apps — data, networking, and main business logic — will largely be shared. However, the user experience (UX) layer must be designed separately for each device. The UX on an Apple Watch is vastly different from an iPhone, Vision Pro, or Mac.</p><h3>4. The Role of Artificial Intelligence: Threat or Opportunity?</h3><p>Artificial Intelligence is the biggest driver of future change. This isn’t just about building smart apps with Core ML or Create ML, but also about the programming process itself.</p><p><strong>Will traditional programming disappear?</strong></p><p>To some extent, yes. Tools like <strong>GitHub Copilot</strong>, <strong>ChatGPT</strong>, and even future Xcode capabilities will lead to:</p><ul><li>Elimination of repetitive coding tasks (like lists, forms, bindings, etc.)</li><li>A shift in developer focus to <strong>architecture design, user experience, and problem-solving</strong></li><li>The need for new skills like <strong>Prompt Engineering</strong>, selecting appropriate AI models, and <strong>AI debugging</strong></li></ul><h3>Will iOS Developers Become Obsolete?</h3><p><strong>Short answer: No.</strong></p><p><strong>More accurate answer: They will be at risk if they don’t adapt their roles and skills.</strong></p><p>Developers who merely stick to writing repetitive code will be vulnerable to AI. However, those who master <strong>“problem-solving with technology,”</strong> <strong>software architecture</strong>, <strong>user experience design</strong>, and <strong>AI interaction</strong> will not only remain relevant but become even more valuable.</p><h3>Essential Skills for Future iOS Developers:</h3><ul><li><strong>Product Thinking</strong> Understanding user needs, designing useful features, and effective collaboration with product teams are key to success.</li><li><strong>System Architecture (System Design)</strong> Knowledge of modern architectural structures, modular and scalable design, and readiness for integration with AI models.</li><li><strong>AI Interaction (Prompt Engineering, Model Selection)</strong> From Prompt Engineering and using Core ML and Vision, to AI Debugging — developers must understand how to interact with intelligent models.</li><li><strong>Soft Skills (Communication, Leadership, Collaboration)</strong> Abilities such as leadership, negotiation, critical thinking, and translating technical concepts to non-technical teams will become extremely valuable.</li><li><strong>Deep UX Understanding for Various Apple Devices</strong></li></ul><h3>In Conclusion: Who Has a Bright Future?</h3><p>The future is bright for those who transform their definition from a “mobile coder” to an “<strong>Apple digital experience architect</strong>.” Swift and Xcode will still be around, but the role we play is changing. The future of iOS development is about creating intelligent, engaging, and multi-platform experiences — and AI will be our assistant on this journey, not our replacement.</p><h3>🧠 What are your thoughts?</h3><ul><li>In 5 years, do you think you’ll spend more time in Xcode or conversing with an AI?</li><li>What skill do you think we should start learning now?</li></ul><p>If you found this article helpful, I’d love to hear your comments or see you share it with fellow developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223d49e77fe3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Errors in the Network Layer in Swift]]></title>
            <link>https://medium.com/@razipour1993/handling-errors-in-the-network-layer-in-swift-895f404d9126?source=rss-654f2d06d65f------2</link>
            <guid isPermaLink="false">https://medium.com/p/895f404d9126</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohammad Razipour]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 23:04:48 GMT</pubDate>
            <atom:updated>2024-07-19T01:02:47.689Z</atom:updated>
            <content:encoded><![CDATA[<p>In iOS programming, proper error management in the network layer is crucial. Given the complexity and variety of HTTP statuses and network errors, using an appropriate structure can aid in simplifying and making the code more readable. In this article, we explore how to use enums to categorize and manage network errors.</p><h4>Defining Network Errors</h4><p>First, we define network errors using NSURLError. These errors encompass various issues that might occur when using URLSession.</p><pre>enum NSURLError: Int, Error {<br>    case unknown = -1<br>    case cancelled = -999<br>    case badURL = -1000<br>    case timedOut = -1001<br>    case unsupportedURL = -1002<br>    case cannotFindHost = -1003<br>    case cannotConnectToHost = -1004<br>    case connectionLost = -1005<br>    case lookupFailed = -1006<br>    case HTTPTooManyRedirects = -1007<br>    case resourceUnavailable = -1008<br>    case notConnectedToInternet = -1009<br>    case redirectToNonExistentLocation = -1010<br>    case badServerResponse = -1011<br>    case userCancelledAuthentication = -1012<br>    case userAuthenticationRequired = -1013<br>    case zeroByteResource = -1014<br>    case cannotDecodeRawData = -1015<br>    case cannotDecodeContentData = -1016<br>    case cannotParseResponse = -1017<br>    case NSURLErrorAppTransportSecurityRequiresSecureConnection = -1022<br>    case fileDoesNotExist = -1100<br>    case fileIsDirectory = -1101<br>    case noPermissionsToReadFile = -1102<br>    case NSURLErrorDataLengthExceedsMaximum = -1103<br>    case secureConnectionFailed = -1200<br>    case serverCertificateHasBadDate = -1201<br>    case serverCertificateUntrusted = -1202<br>    case serverCertificateHasUnknownRoot = -1203<br>    case serverCertificateNotYetValid = -1204<br>    case clientCertificateRejected = -1205<br>    case clientCertificateRequired = -1206<br>    case cannotLoadFromNetwork = -2000<br>    case cannotCreateFile = -3000<br>    case cannotOpenFile = -3001<br>    case cannotCloseFile = -3002<br>    case cannotWriteToFile = -3003<br>    case cannotRemoveFile = -3004<br>    case cannotMoveFile = -3005<br>    case downloadDecodingFailedMidStream = -3006<br>    case downloadDecodingFailedToComplete = -3007<br>    case NSURLErrorInternationalRoamingOff = -1018<br>    case NSURLErrorCallIsActive = -1019<br>    case NSURLErrorDataNotAllowed = -1020<br>    case NSURLErrorRequestBodyStreamExhausted = -1021<br>    case NSURLErrorBackgroundSessionRequiresSharedContainer = -995<br>    case NSURLErrorBackgroundSessionInUseByAnotherProcess = -996<br>    case NSURLErrorBackgroundSessionWasDisconnected = -997<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    var code: Int { return self.rawValue }<br>}</pre><h4>Defining HTTP Status Codes</h4><p>Next, we categorize HTTP status codes using different enums. This categorization helps in managing each HTTP status code easily.</p><pre>/// 1xx Informational<br>enum InformationalStatus: Int, Error {<br>    case continueStatus = 100<br>    case switchingProtocols = 101<br>    case processing = 102<br>    <br>    var description: String { return &quot;&quot; }<br>    var code: Int { return self.rawValue }<br>}<br><br>/// 2xx Success<br>enum SuccessStatus: Int, Error {<br>    case ok = 200<br>    case created = 201<br>    case accepted = 202<br>    case nonAuthoritativeInformation = 203<br>    case noContent = 204<br>    case resetContent = 205<br>    case partialContent = 206<br>    case multiStatus = 207<br>    case alreadyReported = 208<br>    case iMUsed = 226<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    var code: Int { return self.rawValue }<br>}<br><br>/// 3xx Redirection<br>enum RedirectionStatus: Int, Error {<br>    case multipleChoices = 300<br>    case movedPermanently = 301<br>    case found = 302<br>    case seeOther = 303<br>    case notModified = 304<br>    case useProxy = 305<br>    case unused = 306<br>    case temporaryRedirect = 307<br>    case permanentRedirect = 308<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    var code: Int { return self.rawValue }<br>}<br><br>/// 4xx Client Error<br>enum ClientErrorStatus: Int, Error {<br>    case badRequest = 400<br>    case unauthorized = 401<br>    case paymentRequired = 402<br>    case forbidden = 403<br>    case notFound = 404<br>    case methodNotAllowed = 405<br>    case notAcceptable = 406<br>    case proxyAuthenticationRequired = 407<br>    case requestTimeout = 408<br>    case conflict = 409<br>    case gone = 410<br>    case lengthRequired = 411<br>    case preconditionFailed = 412<br>    case requestEntityTooLarge = 413<br>    case requestURITooLong = 414<br>    case unsupportedMediaType = 415<br>    case requestedRangeNotSatisfiable = 416<br>    case expectationFailed = 417<br>    case iAmReapot = 418<br>    case enhanceYourCalm = 420<br>    case unprocessableEntity = 422<br>    case locked = 423<br>    case failedDependency = 424<br>    case reservedForWebDAV = 425<br>    case upgradeRequired = 426<br>    case preconditionRequired = 428<br>    case tooManyRequests = 429<br>    case requestHeaderFieldsTooLarge = 431<br>    case noResponse = 444<br>    case retryWith = 449<br>    case blockedbyWindowsParentalControls = 450<br>    case unavailableForLegalReasons = 451<br>    case clientClosedRequest = 499<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    var code: Int { return self.rawValue }<br>}<br><br>/// 5xx Server Error<br>enum ServerErrorStatus: Int, Error {<br>    case internalServerError = 500<br>    case notImplemented = 501<br>    case badGateway = 502<br>    case serviceUnavailable = 503<br>    case gatewayTimeout = 504<br>    case httpVersionNotSupported = 505<br>    case variantAlsoNegotiates = 506<br>    case insufficientStorage = 507<br>    case loopDetected = 508<br>    case bandwidthLimitExceeded = 509<br>    case notExtended = 510<br>    case networkAuthenticationRequired = 511<br>    case networkReadTimeoutError = 598<br>    case networkConnectTimeoutError = 599<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    var code: Int { return self.rawValue }<br>}<br><br>/// Internal Status<br>enum InternalStatus: Int, Error {<br>    case internetAccessError = 1<br>    case unknown = 2<br>    case invalidUrl = 3<br>    case noData = 4<br>    case unableToDecode = 5<br>    case noPermission = 6<br>    <br>    var description: String { return &quot;\(self)&quot; }<br>    <br>    var code: Int { return self.rawValue }<br>}</pre><h4>General Network Response Status Structure</h4><p>To manage all network statuses and errors, we define a general enum called NetworkResponseStatus that covers all cases.</p><pre>enum NetworkResponseStatus: Error, Equatable {<br>    <br>    static func == (lhs: NetworkResponseStatus, rhs: NetworkResponseStatus) -&gt; Bool {<br>        return lhs.code == rhs.code<br>    }<br>    <br>    case internalStatus(status: InternalStatus, message: String? = nil)<br>    case informational(status: InformationalStatus, message: String?)<br>    case success(status: SuccessStatus, message: String?)<br>    case redirection(status: RedirectionStatus, message: String?)<br>    case clientError(status: ClientErrorStatus, message: String?)<br>    case serverError(status: ServerErrorStatus, message: String?)<br>    case nsurlError(status: NSURLError, message: String?)<br>    <br>    init(statusCode: Int?, message: String? = nil) {<br>        guard let code = statusCode else {<br>            self = .internalStatus(status: .internetAccessError, message: message)<br>            return<br>        }<br>        <br>        if let status = InformationalStatus(rawValue: code) {<br>            self = .informational(status: status, message: message)<br>            return<br>        }<br>        <br>        if let status = SuccessStatus(rawValue: code) {<br>            self = .success(status: status, message: message)<br>            return<br>        }<br>        <br>        if let status = RedirectionStatus(rawValue: code) {<br>            self = .redirection(status: status, message: message)<br>            return<br>        }<br>        <br>        if let status = ClientErrorStatus(rawValue: code) {<br>            self = .clientError(status: status, message: message)<br>            return<br>        }<br>        <br>        if let status = ServerErrorStatus(rawValue: code) {<br>            self = .serverError(status: status, message: message)<br>            return<br>        }<br>        <br>        if let status = NSURLError(rawValue: code) {<br>            self = .nsurlError(status: status, message: message)<br>            return<br>        }<br>        <br>        self = .internalStatus(status: .unknown, message: message)<br>    }<br>    <br>    var description: String {<br>        switch self {<br>        case .internalStatus(let status, let message):<br>            return &quot;Internal Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .informational(let status, let message):<br>            return &quot;Informational Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .success(let status, let message):<br>            return &quot;Success Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .redirection(let status, let message):<br>            return &quot;Redirection Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .clientError(let status, let message):<br>            return &quot;Client Error Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .serverError(let status, let message):<br>            return &quot;Server Error Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        case .nsurlError(let status, let message):<br>            return &quot;NSURLError Status: \(status), \(message ?? &quot;&quot;)&quot;<br>        }<br>    }<br>    <br>    var code: Int {<br>        switch self {<br>        case .internalStatus(let status, _):<br>            return status.code<br>        case .informational(let status, _):<br>            return status.code<br>        case .success(let status, _):<br>            return status.code<br>        case .redirection(let status, _):<br>            return status.code<br>        case .clientError(let status, _):<br>            return status.code<br>        case .serverError(let status, _):<br>            return status.code<br>        case .nsurlError(let status, _):<br>            return status.code<br>        }<br>    }<br>}</pre><blockquote>In any application, the Network Layer, ViewModel, and View may be customized and vary depending on the developer’s needs and preferences. I have prepared a simple example to demonstrate how to use NetworkResponseStatus for handling network responses. I hope to write more about the network layer in my next article.</blockquote><h4>Handling Errors in the Network Layer</h4><p>In the network layer, errors are managed using the NetworkResponseStatus structure. The async/await syntax is used to handle requests and responses efficiently.</p><pre>struct NetworkManager {<br>    <br>    private struct NetworkError: Codable {<br>        let error: String?<br>    }<br>    <br>    static let shared = NetworkManager()<br>    private init() {}<br>    <br>    func performRequest(url: URL) async -&gt; Result&lt;Data, NetworkResponseStatus&gt; {<br>        do {<br>            let (data, response) = try await URLSession.shared.data(from: url)<br>            <br>            guard let httpResponse = response as? HTTPURLResponse else {<br>                return .failure(NetworkResponseStatus(statusCode: nil, message: &quot;Invalid response&quot;))<br>            }<br>            <br>            let networkResponseStatus = NetworkResponseStatus(statusCode: httpResponse.statusCode)<br>            <br>            switch networkResponseStatus {<br>            case .success(let status, _):<br>                if status == .ok {<br>                    return .success(data)<br>                } else {<br>                    return .failure(networkResponseStatus)<br>                }<br>            default:<br>                let decoder = JSONDecoder()<br>                if let model = try? decoder.decode(NetworkError.self, from: data) {<br>                    return .failure(NetworkResponseStatus(statusCode: httpResponse.statusCode, message: model.error))<br>                }<br>                return .failure(networkResponseStatus)<br>            }<br>            <br>        } catch {<br>            return .failure(.internalStatus(status: .internetAccessError))<br>        }<br>        <br>    }<br>}</pre><h4>Using Errors in ViewModel</h4><p>In the ViewModel, errors are managed using the NetworkResponseStatus structure, allowing easy transfer of error messages to the view. Below is an example of how this can be implemented:</p><pre>import Foundation<br>import Combine<br><br>@MainActor<br>class ContentViewModel: ObservableObject {<br>    <br>    @Published var data: Data?<br>    @Published var errorMessage: String?<br>    <br>    func fetchData() {<br>        Task {<br>            let result = await NetworkManager.shared.performRequest(url: URL(string: &quot;https://www.time.ir/&quot;)!)<br>            switch result {<br>            case .success(let success):<br>                self.data = success<br>            case .failure(let failure):<br>                self.errorMessage = failure.description<br>            }<br>        }<br>    }<br>    <br>}</pre><h3>Displaying Errors in SwiftUI View</h3><p>Finally, you can display error statuses in SwiftUI View.</p><pre>struct ContentView: View {<br>    @StateObject private var viewModel = ContentViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            if viewModel.data != nil {<br>                Text(&quot;Data loaded successfully&quot;)<br>            } else if let errorMessage = viewModel.errorMessage {<br>                Text(&quot;Error: \(errorMessage)&quot;)<br>                    .foregroundColor(.red)<br>            } else {<br>                Text(&quot;Loading...&quot;)<br>            }<br>        }<br>        .onAppear {<br>            viewModel.fetchData()<br>        }<br>    }<br>    <br>}</pre><p><a href="https://github.com/RaziPour1993/NetworkLayerErrors">https://github.com/RaziPour1993/NetworkLayerErrors</a></p><p>I hope you found this article helpful. Your feedback and suggestions would be greatly appreciated, and I’m looking forward to hearing any thoughts or recommendations you might have!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895f404d9126" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>