<?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 Dmytro Lupych on Medium]]></title>
        <description><![CDATA[Stories by Dmytro Lupych on Medium]]></description>
        <link>https://medium.com/@dmitrylupich?source=rss-70542c958f08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Cx-NXS7rc3rCE7JP</url>
            <title>Stories by Dmytro Lupych on Medium</title>
            <link>https://medium.com/@dmitrylupich?source=rss-70542c958f08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:25:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmitrylupich/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[What is Sleep Apnea tracked by the Apple Watch 10?]]></title>
            <link>https://medium.com/@dmitrylupich/what-is-sleep-apnea-tracked-by-the-apple-watch-10-be1f49405535?source=rss-70542c958f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/be1f49405535</guid>
            <category><![CDATA[apple-watch-10]]></category>
            <category><![CDATA[watchos]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[apple-watch-ultra]]></category>
            <category><![CDATA[sleep-apnea]]></category>
            <dc:creator><![CDATA[Dmytro Lupych]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 07:16:22 GMT</pubDate>
            <atom:updated>2024-09-10T07:16:22.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b4wAFnfPOtX8JmLYHwjNA.jpeg" /><figcaption>Sleep Apnea detected by Apple Watch 10</figcaption></figure><h4>What is Sleep Apnea?</h4><p>Sleep apnea is a condition where <strong>breathing stops repeatedly</strong> and causes disrupted sleep. If untreated, it can lead to hypertension, type 2 diabetes, and cardiac issues. With new Apple Watch 10 you can now be notified if signs of sleep apnea are detected and receive a report that helps you navigate conversations with your healthcare provider.</p><blockquote>Statistics: 80% of sleep apnea cases are undiagnosed</blockquote><p>The Apple Watch Series 10 is anticipated to feature advanced health monitoring capabilities, <strong>including the potential to detect sleep apnea</strong>, a condition characterized by interrupted breathing during sleep. While previous Apple Watch models have included heart rate, oxygen saturation (SpO2), and sleep tracking, Series 10 enhances these features with more precise algorithms and sensors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0NwzyzdF-DH53wtHcQQeg.png" /><figcaption>Apple Watch 10 — 2024</figcaption></figure><p><strong>Sleep apnea detection</strong> on the Apple Watch 10 may leverage the combination of its built-in SpO2 sensor, ECG, heart rate variability (HRV) data, and accelerometer. These sensors work together to monitor irregularities in breathing patterns and oxygen levels throughout the night. If abnormal dips in oxygen or pauses in breathing are detected, the watch may alert users to potential sleep apnea episodes.</p><p>In addition, advanced <strong>machine learning algorithms</strong> could analyze long-term sleep data, identifying patterns that suggest the presence of sleep apnea. While not a medical device, the Apple Watch Series 10 and <strong>Apple Watch Ultra 2</strong> could serve as a useful tool for early detection, prompting users to seek further diagnosis from a healthcare professional.</p><p>This seamless integration of wearable technology into daily health management represents a promising step toward preventing and managing sleep disorders.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be1f49405535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Composable Architecture: Swift guide to TCA]]></title>
            <link>https://medium.com/@dmitrylupich/the-composable-architecture-swift-guide-to-tca-c3bf9b2e86ef?source=rss-70542c958f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3bf9b2e86ef</guid>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[composable-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dmytro Lupych]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 12:49:53 GMT</pubDate>
            <atom:updated>2024-04-15T12:23:40.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_KLhvKtt0-iG5oY3_wFXQ.png" /></figure><p>Hello! I often hear that MVC pattern is not ideal, but it perfectly fits for small projects. And I totally agree with that statement. But in real life, there are almost no small projects left in the iOS development world. Apps become bigger and bigger each year, and business and user demands for mobile apps are growing exponentially.</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><p>That’s why modern app architecture should be able to scale and satisfy the needs of the developers. I learned a lot of different approaches to achieving scalability. But TCA way is my favorite one right now.</p><h4>Problems with M+Patterns</h4><p>Here we can refer to MVC, MVVM, MVP, and other M-like patterns. What they have in common — they are easy to learn and implement, and they work great for local isolated features. But when the app starts growing, some problems can arise.</p><p>Among them:</p><ul><li>passing data between separate parts of the app</li><li>how should we connect features</li><li>integration tests</li><li>modularisation</li></ul><p>Imagine the situation: you have a complex navigation stack with different presentations of 20 screens. And when you press the button on the last screen, you need somehow react to that tap on the first screen. How can you achieve that? There are different approaches that I’ve used.</p><p>What you can use here:</p><ul><li>the shared data bus, like Notification Center</li><li>pass some closure/delegate/publisher to every screen</li><li>try some service-oriented approach (SOA) passing data</li><li>or make use of the responder chain and sendAction(#selector) method</li></ul><p>All these things work, but they are not self-explaining and obvious for new devs in the project, it’s hard to test them, you can easily miss something and receive undesired behavior, and isn’t tough to standardize them for a team. Fortunately, we can use TCA framework to handle all that problems in a strict type-safe way.</p><h4>What is TCA</h4><p>The Composable Architecture is a Swift adaptation of the Redux framework, that matches perfectly with SwiftUI, UIKit, Combine, and even Modern Concurrency (async/await). It follows the Unidirectional Data Flow approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMaJN8hTplyyysiVz9ECXA.png" /><figcaption>Unidirectional Data Flow</figcaption></figure><p>The concepts around TCA are very simple, I promise you will like them:</p><ul><li>isolation</li><li>composition</li><li>pure functions</li><li>managed side effects</li></ul><p>The learning path could be pretty hard at the start. But in general, TCA’s concepts are straightforward and the more you learn, the more the puzzle gets cleared. Code written using TCA could potentially look like that. Here is described simple logic of a news app: downloading a list of posts with pagination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpEfyWNh7_nvX4fhifeDiA.png" /><figcaption>Example of simple Reducer in The Composable Architecture</figcaption></figure><p>Please, don’t get scary of that buzz words. So lets dive in.</p><h4>TCA Components: State, Action, Reducer, Environment, Effect and Store</h4><p>Main Composable moving parts are basically Reducer and Store. Environment, State and Actions are user-defined and accomplish first two.</p><p><strong>State</strong> — structure model of your app. It can contain some data, like list of news, bool properties isLoading, that shows or hide spinner indicator, nested states of other features of the app. Most properties are defined as variable, so we can change three values easily. Conforms to Equatable protocol.</p><p><strong>Action</strong> — enumeration that represents all possible actions emitted by the app. It can also have nested other feature actions inside associated values. As state also conforms to Equatable protocol.</p><p><strong>Reducer</strong> is entity represented by pure function, where all the business logic could happen. Reducer accepts actions and based on them mutates state (that’s why we mark properties as var, not let). Also it returns special type called Effect (EffectTask in new version of framework).</p><p><strong>Effect</strong> (EffectTask in a new version of architecture) is a wrapper around some pice of work (usually asynchronous work). Effect should do some work, like network request, and based on that result return new action, that will be feed back to Reducer by Store.</p><p><strong>Store</strong> connects everything together. Just check what accepts its initialiser. It requires initial state and reducer. Store receives some action, then passes it to reducer along with current state, and based on that mutation gets new state.</p><p><strong>Environment</strong> — is basically object with help of which we can produce side-effects. It’s perfect place to store database or networking methods, some calculations or other things, that help us communicate with outside world.</p><p>Let’s sum up. Why is it called UDF? Because our data flows in a single direction: the View emits some Action, that Action goes to the Store, which calls the Reducer to recalculate State, and the new State is published to the View. Does it sound clearer now? Alright, let’s design our first feature. Imagine we want to create a News App with a main page containing posts, infinite load pagination, and post details on a new screen.</p><p>I will not focus on all the boilerplate view code, instead, I will explain how things are connected to each other. Firstly, we will create our main screen ListFeature, defining a struct with State and Action types inside, which conforms to ReducerProtocol. Additionally, we need to add a reducer here, and there are two options: defining a body property of type some ReducerProtocolOf&lt;Self&gt; or a reduce function. I personally prefer the var body approach more, as it looks like the native SwiftUI body property.</p><p>Inside the state, we will have only three properties: news, page, and isLoading. This is sufficient to describe our screen. Now we need to think about the Actions that can influence our view. Here are some examples:</p><pre>public struct ListFeature: ReducerProtocol {<br>    //MARK: - Environment<br>    private let environment: ListEnvironment = .init(<br>        newsService: NewsService(<br>            network: Networking(<br>                session: .shared<br>            )<br>        )<br>    )<br>    //MARK: - State<br>    public struct State: Equatable {<br>        public var page: Int = 1<br>        public var news: [NewsModel]<br>        public var isLoading: Bool = false<br>        public init(news: [NewsModel]) {<br>            self.news = news<br>        }<br>    }<br>    //MARK: - Action<br>    public enum Action: Equatable {<br>        case start<br>        case didScrollToBottom<br>        case details(NewsModel)<br>        case onAppear(NewsModel)<br>        case newsResponse(Result&lt;[NewsModel], NAError&gt;)<br>    }<br>    //MARK: - Reducer<br>    public var body: some ReducerProtocol&lt;State, Action&gt; {<br>        Reduce { state, action in<br>            switch action {<br>            case .start, .didScrollToBottom:<br>                state.isLoading = true<br>                return environment<br>                    .newsService<br>                    .news(for: state.page)<br>                    .receive(on: DispatchQueue.main)<br>                    .catchToEffect(Action.newsResponse)<br>            case let .newsResponse(.success(news)):<br>                state.isLoading = false<br>                state.page += 1<br>                state.news += news<br>                return .none<br>            case let .newsResponse(.failure(error)):<br>                state.isLoading = false<br>                return .none<br>            case .details:<br>                return .none<br>            case .onAppear(let post):<br>                return post == state.news.last ?<br>                EffectTask(value: Action.didScrollToBottom) : .none<br>            }<br>        }<br>    }<br>    public init() {}<br>}</pre><p>Also, let’s create an environment which will contain code related to uploading news from the Internet and pagination. Now it’s time for the most interesting part — the Reducer. It accepts two things: an inout state and an action. Inside the body property, let&#39;s define the reducer with state and action parameters and switch over the action. Imagine some logic that can be added to each case of possible actions.</p><p>For example, in the case when the screen just appeared or our list was scrolled to the bottom, we need to call the environment and try to load more posts. The networking request is a simple Combine stream, but notice how we mapped the response to an Action case and converted it to an Effect.</p><pre>return environment<br>                  .newsService<br>                  .news(for: state.page)<br>                  .receive(on: DispatchQueue.main)<br>                  .catchToEffect(Action.newsResponse)</pre><p>This is how we deal with side-effects. That EffectTask with an Action inside will be fed back to the Reducer function and will mutate the state and/or produce a new Effect. In case we don’t have side-effects (look at details case in reducer), we can simply return a special Effect.none from the Reducer, indicating that we are done and don’t need to call the reducer again.</p><p>This NewsService Effect will lead us to the new Action case newsResponse. It has Result type inside, so we can go from here to success and failure case. In case of failure we will handle error some how. In case of success, we can extract the new blog posts and append them to our array of existing posts, and don&#39;t forget to increase the current page by 1. It seems the main work is done: we can load new posts from the web and update our state with new posts. Also we are able to toggle isLoading property to indicate loading status of the upcomming posts. Now let&#39;s see how things are going in the UI layer.</p><pre>import SwiftUI<br>import Combine<br>import ComposableArchitecture<br><br>//MARK: - View<br>public struct ListView: View {<br>    private let store: StoreOf&lt;ListFeature&gt;<br>    <br>    public init(store: StoreOf&lt;ListFeature&gt;) {<br>        self.store = store<br>    }<br>    <br>    public var body: some View {<br>        WithViewStore(self.store) { viewStore in<br>            List(viewStore.news, id: \.id) { post in<br>                ListItem(model: .init(post: post))<br>                    .onTapGesture { viewStore.send(.details(post)) }<br>                    .onAppear { viewStore.send(.onAppear(post)) }<br>            }.toolbar {<br>                if viewStore.isLoading {<br>                    ProgressView()<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>ListView is initialized with StoreOf&lt;ListFeature&gt;. And to be able to react to state changes, we should wrap this store in a WithViewStore wrapper. Inside WithViewStore, we have the viewStore parameter that serves two purposes:</p><ul><li>observe state changes</li><li>send some actions</li></ul><p>For example, in the onAppear of ListItem, we are sending the ListFeature.Action.onAppear action to the store. As described above, that action will trigger a new blog post request if we reach the bottom of the list.</p><p>Hint! We can optimize some things here. If we need to observe only one property of the state, we can call WithViewStore with the observe parameter, passing it to the closure. This way, our view will react only to particular property changes rather than the whole state changes. Also, explore other wrappers like SwitchStore, IfLetStore, and others. They can be quite useful for some non-standard state modeling.</p><h4>Combining Reducers</h4><p>The power of TCA is in combining reducers. In general our app will look like a tree or a graph, so we can reach any node from any starting point. Go to AppFeature and check how its reducer is implemented.</p><pre>import Combine<br>import SwiftUI<br>import Foundation<br>import ListFeature<br>import DetailsFeature<br>import ComposableArchitecture<br><br>public struct AppFeature: ReducerProtocol {<br>    //MARK: - State<br>    public struct State: Equatable {<br>        public enum Route: Hashable {<br>            case details<br>        }<br>        var path: [Route] = []<br>        var listState: ListFeature.State<br>        var detailsState: DetailsFeature.State?<br>        static let initial: Self = .init(<br>            path: [],<br>            listState: .init(news: []),<br>            detailsState: .none<br>        )<br>    }<br>    //MARK: - Action<br>    public enum Action: Equatable {<br>        case list(ListFeature.Action)<br>        case details(DetailsFeature.Action)<br>        case path([State.Route])<br>    }<br>    //MARK: - Reducer<br>    public var body: some ReducerProtocolOf&lt;Self&gt; {<br>        Reduce { state, action in<br>            switch action {<br>            case let .list(.details(post)):<br>                state.detailsState = .init(post: post)<br>                state.path = [.details]<br>                return .none<br>            case .path(let newPath):<br>                state.path = newPath<br>                return .none<br>            default:<br>                return .none<br>            }<br>        }<br>        <br>        Scope(<br>            state: \.listState,<br>            action: /Action.list<br>        ) {<br>            ListFeature()<br>        }<br>    }<br>}</pre><p>You can observe plain reducer and some Scope. That Scope object acts like a bridge, so you can connect child reducers with parent. Scope accepts three parameters: WritableKeyPath for childState, CasePath for action and child ReducerProtocol.</p><p>There is special syntax for CasePath (check in PointFree Repo). So instead of providing full closure, we can use \ for keyPath and /for CasePath and benefit from shorter declarative syntax. Yes, it looks wired, but I promise you will get use to it someday:)</p><p>What we achieved here, that now our child and parent reducers are connected. And we can react on child actions inside parent reducer using nested enum cases. Look at case let .list(.details(post)) — this is how actions propagated from child to parent. Pressing on some post on list page will trigger that action on AppFeature reducer and will navigate to details page. Also we can update child’s state from parent reducer, in case if we need to use some data from upstream.</p><pre>import SwiftUI<br>import ListFeature<br>import DetailsFeature<br>import ComposableArchitecture<br><br>struct AppView: View {<br>    let store: StoreOf&lt;AppFeature&gt;<br>    <br>    var body: some View {<br>        WithViewStore.init(self.store) { viewStore in<br>            NavigationStack(<br>                path: viewStore.binding(<br>                    get: \.path,<br>                    send: .path([])<br>                )<br>            ) {<br>                ListView(<br>                    store: store.scope(<br>                        state: \.listState,<br>                        action: AppFeature.Action.list<br>                    )<br>                )<br>                .navigationBarHidden(false)<br>                .onAppear {<br>                    viewStore.start()<br>                }<br>                .navigationDestination(for: AppFeature.State.Route.self) { route in<br>                    switch route {<br>                    case .details:<br>                        IfLetStore(<br>                            store.scope(<br>                                state: \.detailsState,<br>                                action: AppFeature.Action.details<br>                            )<br>                        ) { store in<br>                            DetailsPage(store: store)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Here is some View code that describes how to navigate between scenes. Using Optional wrapper around DetailsFeature state we can show or hide it, based on it’s value. When we are on a List screen, DetailsFeature is nil, but when we press on some post, DetailsFeature is initialized and presented in NavigationStack. Optional state is a good candidate to be wrapped in IfLetStore.</p><h4>Epilogue</h4><p>What is the most valuable benefit for me in TCA is its ability to control every action in the code base. With a combination of reducers, you can easily react to any button press, network response, or notification in any part of the app. Short declarative syntax and pre-build ViewStores give us flexibility and freedom to model the state of our app. As you see, reducers are not coupled together, so we are able to move features into separate self-contained modules (for example using SPM modules inside single app).</p><p>Thanks for reading! Full project can be found on Github — <a href="https://github.com/DmitryLupich/NewsApp/tree/TheComposableAchitecture">NewsApp</a>. Visit PointFree’s <a href="https://github.com/pointfreeco/swift-composable-architecture">Composable Architecture repo on Github</a>, where you can find source code, inspiration and examples. Also, connect with me on <a href="https://www.linkedin.com/in/dmitrylupich/">LinkedIn</a>.</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3bf9b2e86ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create custom Publisher in Combine]]></title>
            <link>https://medium.com/@dmitrylupich/swift-combine-custom-publisher-6d1cc3dc248f?source=rss-70542c958f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d1cc3dc248f</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Dmytro Lupych]]></dc:creator>
            <pubDate>Sun, 23 Feb 2020 16:37:21 GMT</pubDate>
            <atom:updated>2024-04-15T12:24:22.201Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Learn how to create your own Combine publisher in Swift</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqwR0e-RP2iJka8uew_JeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6cNKsMejgrlI9grVXg2OQ.jpeg" /></figure><p>If you are reading this article, I dare to assume that you’ve already tried Combine in your pet project. And you have some questions about this new and exciting Apple’s framework. For example how to create your publishers in Combine? This article can help you understand the basics of the mechanism of creating custom publishers for different needs.</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><p>If you tried to send some network requests using Combine, you should be familiar with <strong>URLSession.shared.dataTaskPublisher</strong>. It simply sends a response to its subscriber. In this tutorial, we will implement our own dataTaskPublisher. But the process of creation subscription is pretty generic, so after this tutorial, you’ll probably be able to create any publisher for your own needs: for UIKit Controls, for KeyBoard, TableViews and other components.</p><p>First of all, let’s learn from which parts consist of each publisher-subscriber chain. It’s obvious, that we have a publisher — that thing, which gives us values, and a subscriber, which requests this values for its own purpose. But the main part of this collaboration is usually hidden. I’m talking about subscription by itself, and that’s where all the magic happens.</p><p>Subscription is like <em>Interactor</em>, <em>ViewModel</em> or simply <em>Brain</em> of publisher-subscriber collaboration. The publisher creates a subscription with all required dependencies and gives it to the subscriber. After this, the subscription starts acting and processing values over time. Then subscriber consumes these values and we can receive them in the sink closure.</p><p>Let’s sum up. To create a working stream we need three things:</p><ul><li>Publisher</li><li>Subscription</li><li>Subscriber</li></ul><h3>Subscription</h3><p>Let’s start with the main part — subscription. We should create a class called DataSubscription to get the ability to pass it by reference. It will have some private fields: session, subscriber and request. All these properties will be constructed via the initializer. And basically, the publisher will give all of them to the subscription. Also, for better encapsulation, you can mark the DataSubscription class as private, because we don’t need to access it directly from outside Publishers extension.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e182131a61bef0631e9da7200aca7a/href">https://medium.com/media/26e182131a61bef0631e9da7200aca7a/href</a></iframe><p>Our DataSubscription is a generic class that implements Subscription protocol and has <em>where</em> clause, which states, that subscribers associated types are Data for Input, and Error for Failure. Inside this class, we have private method <em>sendRequest</em>, which wraps URLSession’s dataTask with completion. Inside the session’s callback, we simply tell our subscriber to receive the next value in case we have some data, or receive the completion event with the raised error.</p><p>Also, in the cancel method, we will simply <em>nil</em> the link to the subscriber, to break the chain. So we will have and ability to manually cancel this subscription in the future. It looks pretty simple, doesn’t it? Now let’s create a DataPublisher publisher to utilize this subscription.</p><h3>Publisher</h3><p>If you’ve already tried to see how publishers are implemented in Combine, you should notice that they are nothing then structures. We also will define the DataPublisher structure with a single required property — <em>urlRequest</em>. Also, our publisher should conform to the Publisher protocol, to be able to act in Combine’s world. After conforming to that protocol, the compiler will add receive method and two type aliases to your code. For Output type alias we will sign Data type, and for Failure — Error protocol. Okay, now we need to fulfill the receive method.</p><p>Inside this method, we need to do two things: create the subscription and give it to the subscriber. That’s how it looks like in code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be3d32e705cccb0af75c4fd21fed217b/href">https://medium.com/media/be3d32e705cccb0af75c4fd21fed217b/href</a></iframe><p>Now we’re almost ready to present our own publisher. One more step left!</p><h3>Subscriber</h3><p>To make the subscriber be able to receive values from out DataPublisher, we should make some property or method, that will return an instance of DataPublisher. Let’s extend URLSession with <em>dataResponse</em> method, that will take a URLRequest as it’s single parameter, and return us DataPublisher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a78bc04a97e0985946f34cd3c7dc229d/href">https://medium.com/media/a78bc04a97e0985946f34cd3c7dc229d/href</a></iframe><p>Now we can simply call <em>URLSession.shared.dataResponse(for request: URLRequest)</em> to receive some data from remote server. As you see, nothing complex here. Now you can create custom publishers for any object that you want, be sure to try to create your own. The full project can be found in <a href="https://github.com/DmitryLupich/Combine-URLSession-Publisher">GitHub</a>, also there is one more repository named <a href="https://github.com/DmitryLupich/Combine-UIKit">Combine-UIKit</a>, where you can find an implementation of custom publishers for different UIKit components.</p><p>As usual, if you have some questions - feel free to ask them in comments. If this article was useful for your needs, press clap and share it to say thanks 😉</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d1cc3dc248f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Monads, Functors and Applicatives with examples]]></title>
            <link>https://medium.com/@dmitrylupich/swift-monad-functor-applicative-806bb34c68c5?source=rss-70542c958f08------2</link>
            <guid isPermaLink="false">https://medium.com/p/806bb34c68c5</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Dmytro Lupych]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 19:49:32 GMT</pubDate>
            <atom:updated>2024-04-15T12:24:13.713Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Learn the concept of functor, monad and applicative</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RK6SF6e7zF5_fKFltHoDZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-T-iCPPLwKlwxhIsDWPLPQ.jpeg" /></figure><p>Every developer which starts learning functional reactive programming eventually faces such concepts, like functor, applicative and monad. For the first time, they sound really scary, but there is nothing complex behind these words. In today’s lesson, I will try to explain to you these simple, but not very familiar concepts for imperative programming.</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><p>To make this article more understandable we will write together some code. Because from my perspective, programmers perceive and assimilate information better, when they can try it in their favorite IDE. So, my examples will be very simple, but it will be enough to understand the basics of further learning.</p><h3>Values in context</h3><p>If you are an imperative programmer, you are basically familiar with properties. Each property has a type and it’s own value. In the functional world, this concept is a little bit different. So, first of all, we need to understand what does it mean value in a context. For simplicity, imagine a variable, for example, <strong>var number = 7</strong>. And then, imagine a box, where you can put your value.</p><p>This box is a simple concept of our context. The next thing, you should accept, is that our box can have a value, or can be empty (like an array or real box from the physical world). The value wrapped in a context means that we can’t reach this value directly, but we can try to extract it somehow, in case our container is not empty. Nothing complicated here — everything is pretty simple and understandable.</p><p>I hope, that at this moment everything is clear for you. An attentive reader can notice, that our box concept resembles Optional type in Swift. And he will be absolutely right! Like a box, Optional can have a value or can be nil, if a value is absent.</p><blockquote>A little spoiler: Optional is a functor and even a monad.</blockquote><p>But first things first. Let’s create our own optional-like type, and on its example learn how to deal with functors, monads, and applicatives. For further experiments, we define generic enum of type Box&lt;T&gt; with two cases: some — when we have a value, and empty — when our box is empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3fd8a298b544260ae91fe82c18a9e44/href">https://medium.com/media/f3fd8a298b544260ae91fe82c18a9e44/href</a></iframe><p>If everything is clear for you, it’s time to introduce a functor.</p><h3>Functor</h3><blockquote>In a nutshell: functor is a type, that implements map function. Like Optional, Collection and Result types in Swift.</blockquote><p>Okay, now imagine that you have a variable of type Int that is equal to 7. And then you want to increase it by 3, to get 10. What do you do in the imperative paradigm? Right, you just write 7 + 3 and you get your 10. But how can we add 3 to our value 7, which is wrapped in a context?</p><blockquote>Box(7) + 3 -&gt; What? Type Error.</blockquote><p>To do such kind of computation, we need some function, that will execute computation in a case when the box is not empty, or fail/return “empty box” if the box has no value inside.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f8a4a2170e21219fc8868f17eeaa7ef/href">https://medium.com/media/9f8a4a2170e21219fc8868f17eeaa7ef/href</a></iframe><p>What we’ve done here: we define add a function that accepts Int value as a parameter, perform some computation and returns Box of the same type Int. Pretty straight-forward. Now, we can rewrite this expression to make it more generic. Here, where map function comes in. What we want to achieve: is to pass any function with the signature (T) -&gt; U as a parameter to map and to become independent of a specific type. That’s how we do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0436f6e022004198536bf5329c48565/href">https://medium.com/media/c0436f6e022004198536bf5329c48565/href</a></iframe><p><strong>What we have here:</strong></p><ul><li>generic map function that accepts function of type (T) -&gt; U as its single argument and has a return type Box&lt;U&gt;</li><li>in the function body, we do simple switch case</li><li>if there is a value, we call f-function on it, get a result of type U, wrap it back to Box&lt;U&gt; type and simply return it</li><li>if there is no value, we just return an empty case of new type U: Box&lt;U&gt;</li></ul><p>Now using map-function, we can apply any function to our “box” that accepts T as a parameter and returns a new U type. Thereby we get an ability to deal with value wrapped in a context. And now we are ready to define a functor.</p><blockquote>A functor applies a function to a value wrapped in a context.</blockquote><p>In other words: functor is a type, that implements map function which knows and describes how to apply a function to a wrapped value.</p><h3>Applicative</h3><p>If at this point everything is clear for you, then you are ready to learn what is applicative. If not, feel free to read about functor again, make your favorite coffee and come back to this part of the article later.</p><p>In the previous chapter we’ve learned about values in context and how to apply functions to them using functors. But what should we do if we want to apply a wrapped function to a wrapped value? Now we need something more powerful than the map. Let’s extend our Box type with apply function, which will simply switch on function in context and on a value in context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/188041cd7e14fe700b9785a6f8ee09c6/href">https://medium.com/media/188041cd7e14fe700b9785a6f8ee09c6/href</a></iframe><p>Now pay attention to the first some case. Does nested switch statement remind you of anything? This code does pretty the same our map function does. So let’s refactor it a little bit and replace the nested switch with the map function. Excellent!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4aa44dd2d467bab8e6b9a43b285c89f/href">https://medium.com/media/c4aa44dd2d467bab8e6b9a43b285c89f/href</a></iframe><p>So our computation will return some value wrapped in a context only in case if there is some function in a parameter box and some value inside our box. In other cases apply will return empty box. Sounds good? Let’s define what applicative is. I hope at this point you can make a definition of this concept by yourself.</p><blockquote>Applicative applies a wrapped function to a wrapped value.</blockquote><p>Again, if everything is clear for you, we can move forward.</p><h3>Monad</h3><p>Very good. Now we have the last and the most hard-sounding concept — monad. Just read its definition and try not to get mad:</p><blockquote>A monad applies wrapped function that returns wrapped value to the wrapped value.</blockquote><p>But don’t be afraid, you’ve already successfully learned about functors and applicatives. I promise the monad will be a piece of cake for you. Let’s define flatMap function for Box type and see, what exactly monad is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91171fa69cdf8529b69dd768f4bc1982/href">https://medium.com/media/91171fa69cdf8529b69dd768f4bc1982/href</a></iframe><p>The argument of flatMap function by itself returns Box&lt;U&gt;, not U-type as functor’s or applicative’s parameter function does. So the monad does exactly what it should do: it takes a function that returns wrapped value and applies this function to the wrapped value.</p><p><strong>Some Examples</strong></p><p>After learning these concepts, it should be clear for you, that optional, array even Result types in Swift all are functors and monads. Why? Simply because they implement map and flatMap functions, which in turn know how to perform computations when there is a value inside or there is an absence of value.</p><p>Let’s see, how it can be useful in your daily work as an iOS Developer. For example optional. Imagine some function that requires integer as a parameter and do some stuff with it. But instead of an integer value, we have our Int wrapped in optional type. What do you usually do, is something like this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7454a444293b8edea04861a456791fd9/href">https://medium.com/media/7454a444293b8edea04861a456791fd9/href</a></iframe><p>But how can we refactor this code? Let’s simply use our new knowledge and try map function, which applies a function to a wrapped (optional in our case) value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/195bde80193ebffcefd6a520b18d018d/href">https://medium.com/media/195bde80193ebffcefd6a520b18d018d/href</a></iframe><p>Now our code looks better, shorter and more descriptive. Good, next we will try another example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30243ecfe0a7aa8cf7646bb2f0b83904/href">https://medium.com/media/30243ecfe0a7aa8cf7646bb2f0b83904/href</a></iframe><p>Check out the type of someModel property. String?? Double optional. Wait, what? Our optional try? The function returns an optional String, and the map function wraps it also into nested optional, which has no sense. So how we can refactor it and flatten nested optional? We should use something, that applies a function to the wrapped value, that by itself returns wrapped value. Doesn’t resemble anything? Exactly, it’s the monad, which provides us with flatMap function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6806f0c355dd2e6bc52143f7f5982b4c/href">https://medium.com/media/6806f0c355dd2e6bc52143f7f5982b4c/href</a></iframe><p>Or even more complex nested optionals. Here the result type is Optional&lt;Optional&lt;Int&gt;&gt;??</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd76ebf55a2931a9c8e2fe5d813da426/href">https://medium.com/media/cd76ebf55a2931a9c8e2fe5d813da426/href</a></iframe><p>But, using flatMap instead of each map function, we can flatten and reduce our nested optional to the single optional resulting value. The same thing is with the Result type in Swift. It is also a functor and a monad. Just look at this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c7219af96b2a4ae39003960a61aed83/href">https://medium.com/media/7c7219af96b2a4ae39003960a61aed83/href</a></iframe><p>I hope this article was interesting and helpful for you. If you received any new knowledge or you still have some questions, write about it in the comments.</p><blockquote>Check out my water tracking app <a href="https://apps.apple.com/ua/app/waterme-tracker-and-reminder/id6480010510">WaterMe</a> build with SwiftUI</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806bb34c68c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>