<?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 Mike Haidan on Medium]]></title>
        <description><![CDATA[Stories by Mike Haidan on Medium]]></description>
        <link>https://medium.com/@misha.gajdan?source=rss-c93db64c02c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aFi34kd8HUSce_syA8_jFg.jpeg</url>
            <title>Stories by Mike Haidan on Medium</title>
            <link>https://medium.com/@misha.gajdan?source=rss-c93db64c02c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:46:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@misha.gajdan/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[Unit Testing in iOS. Asynchronous functions.]]></title>
            <link>https://medium.com/@misha.gajdan/unit-testing-on-ios-asynchronous-functions-b6b74582828a?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b74582828a</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Mon, 27 May 2024 10:17:02 GMT</pubDate>
            <atom:updated>2024-05-27T10:29:26.177Z</atom:updated>
            <content:encoded><![CDATA[<p>During an iOS developer career, in some period of time, software engineers start writing unit tests. It’s like the first wall to prevent any bugs. But when it comes to asynchronous functions, there might be some problems. The question is: what is the proper way of testing asynchronous functions? In this article I’ll show you how it can be done. In the end, you’ll see that it’s even possible to make a linear function from an asynchronous one.</p><p>Let’s use this simple class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1242ec2d176f06550baad9f83bff7ec8/href">https://medium.com/media/1242ec2d176f06550baad9f83bff7ec8/href</a></iframe><p>So this class has one function <em>checkIfAppleWorks</em> which makes an API call to `<a href="https://developer.apple.com/">https://developer.apple.com</a>`. Depending on the response it updates the <em>appleState</em> property. The class doesn’t have practical use and can be implemented in a better way, but, for teaching use, it shows common problems. It has API calls + calls from different threads.</p><p>Now, let’s add a test class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/498e8a731ebac66f1952f1944634f950/href">https://medium.com/media/498e8a731ebac66f1952f1944634f950/href</a></iframe><p>For async calls we use <a href="https://developer.apple.com/documentation/xctest/xctestcase/1500899-expectation"><em>expectation</em></a> with <a href="https://developer.apple.com/documentation/xctest/xctestcase/2806856-wait"><em>wait</em></a> functions.</p><p>Simply speaking, <em>wait</em> suspends your test till your asynchronous function does something.</p><p>In gist above:<br>1 — we create expectation <br>2 — we set waiting expectation with timeout<br>3 — after we received a response from the function, we call <em>fulfill</em> to mark an expectation as having been met.</p><p>Currently this test is not reliable. Here is why:<br>1. What if it will take more then 2 second to receive a response<br>2. Not possible to test “error” state.<br>3. If API calls for some reason returns error, the tes will be failed</p><p>As you may have noticed, the main reason is <em>URLSession</em>. <em>URLSession</em> is a singleton class + it makes a remote API class. <br>In a proper way, our tests should not depend on the server behavior, our tasks, depending on the server response, handle it correctly. <br>How can we solve this? Of course by using <strong>Dependency Injection</strong> + <strong>protocols</strong></p><p>Let’s add this protocol to replace <em>URLSession</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1591d6724a342ea042b8eac7571e1c28/href">https://medium.com/media/1591d6724a342ea042b8eac7571e1c28/href</a></iframe><p>This Protocol hides implementation details of a <em>URLSession</em>. Now it’s possible to update <em>AppleChecker</em>, by replacing <em>URLSession</em> by <em>URLSessionProtocol</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe3ecbb2f6e12ff337fcaaa6f40e6d7/href">https://medium.com/media/fbe3ecbb2f6e12ff337fcaaa6f40e6d7/href</a></iframe><p>1 — Add stored property, which will be used for API Calls.<br>2 — Set it in <em>init</em>.<br>3 — Replace the old <em>URLSession</em> function with the new one and update the <em>dataTask</em> function.</p><p>Because <em>URLSession</em> was replaced by <em>URLSessionProtocol</em>, in our test we can simulate (or “mock” as it’s usually called) server response. Now let’s update TestClass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4eaf719a16cebd0ed4cda88f8d1f901/href">https://medium.com/media/e4eaf719a16cebd0ed4cda88f8d1f901/href</a></iframe><p>1 — Create a <em>URLSession</em> “double” class (About test doubles you can read in this article (<a href="https://medium.com/@misha.gajdan/unit-testing-in-ios-test-doubles-4be44163470d">https://medium.com/@misha.gajdan/unit-testing-in-ios-test-doubles-4be44163470d</a>), but, if shortly, <em>Stub</em> name used for objects which, return preprogrammed answer).</p><p>2 — Property where programmed response will be set.<br>3 — Instead of calling an API call, return a preprogrammed answer.</p><p>And now go to the <em>AppleCheckerTests</em>. Seems like there are a lot of changes, but, in reality, it’s quite simple.</p><p>4 — Create an instance of a urlSession stub, which will be used to “set” server response.<br>5 — Initialize the property in `<em>setUp</em>` function.<br>6 — Because we can control the response of a “urlSession”, now we can test 2 states. When the response is successful and when it’s not. <br>7 — Set “expected” response for a particular test. For <em>testCheckIfAppleWorksSuccessResponse</em> it has to be some <em>Data</em>, for <em>testCheckIfAppleWorksSuccessFailure</em> it has to be an error.</p><p>That’s all, by replacing <em>URLSession</em>, we have much more control over the class.</p><p>But there is one problem. <em>AppleChecker</em> is still an asynchronous class due to <em>DispatchQueeue</em> used in the <em>checkIfAppleWorks</em> function. <br>As many as we have asynchronous calls, we will need to repeat the “<em>expectation</em>/<em>wait</em>” sequence. And if you have 10 or 100 tests it becomes really annoying + it’s hard to read and understand tests. Would be much better to have a linear one.</p><p>How can it be achieved?<br>First option, by adding small extension to “<em>XCTestCase</em>”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fe2684a4a19b1fc5f68da8b4e2335ac/href">https://medium.com/media/5fe2684a4a19b1fc5f68da8b4e2335ac/href</a></iframe><p>It’s a delay function, which adds a small delay to your tests, so you don’t need to repeat the “<em>expectation/wait</em>” sequence.<br>Now, let’s update <em>AppleCheckerTests</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adea31cfb933d153fccd773d98ed1fa1/href">https://medium.com/media/adea31cfb933d153fccd773d98ed1fa1/href</a></iframe><p>This one reads much better and reads easier. What was done, it’s just added a delay from the <em>XCTestCase</em> extension (comments 1, 2 from the gist above). Because of a delay, we do not need to use “<em>expectation/wait</em>” anymore.</p><p>Even though it works, it still looks like (and it is) a “hack” and this “hack” can be fixed as well. As I mentioned, the issue is <em>DispatchQueue</em>. By using the same <strong>Dependency Injection</strong> principle, as it’s done with <em>URLSession</em>, we can remove asynchronous entirely.<br>Let’s add a protocol and an extension:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0087774d2d9f21f05692b190a38af68e/href">https://medium.com/media/0087774d2d9f21f05692b190a38af68e/href</a></iframe><p>And now let’s go to “<em>AppleChecker</em>” and add some updates:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc19c78b9877cfb20fb9ad77da97f074/href">https://medium.com/media/fc19c78b9877cfb20fb9ad77da97f074/href</a></iframe><p>1 — Create an instance of <em>ThreadService</em>, which replaces <em>DispatchQueue</em>.<br>2 — Set it in <em>init</em> by using <em>DispatchQueue.main.</em><br>3 — Replace <em>DispatchQueue.main</em> by <em>mainQueue.</em></p><p>That’s all that has to be done in the class. Now let’s go to the tests and create Test double for “<em>ThreadService</em>”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d54c803d637171a4bf284d275df30662/href">https://medium.com/media/d54c803d637171a4bf284d275df30662/href</a></iframe><p>It’s a simple “<em>Fake</em>” object. Which doesn’t do anything, just returns completion.</p><p>And final update to <em>AppleCheckerTests</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0634c9d890d679a4712ddc01ce45f68d/href">https://medium.com/media/0634c9d890d679a4712ddc01ce45f68d/href</a></iframe><p>1 — Create instance of <em>ThreadServiceFate</em>.<br>2 — Init property in <em>tearDown</em> function .<br>3 — Pass <em>mainQueue</em> to <em>AppleChecker</em>.</p><p>Because, <em>AppleChecker</em> does not depend on <em>DispatchQueue</em> and <em>URLSessions</em> anymore and <em>ThreadServiceFake</em> and <em>URLSessionStub</em> are a linear/sequence class, which call their function in the same queue. All tests are sequential/linear and do not require any exception/wait sequences nor delays . <br>Both tests (with closure and without, comments 4 and 5) will work because <em>checkIfAppleWorks</em> is sequential and makes calls in the same queue.</p><p>What we gave at the end. Now our tests are readable, fast and reliable.</p><p>That’s all. By applying a simple Dependency injection principle, you can make any class sequential.</p><p>I hope this article was helpful and these tips will help you to write better and understandable tests.</p><p>Thank you for reading ❤️.</p><p>Check out my other articles:</p><p><a href="https://medium.com/@misha.gajdan/mvvm-binding-in-uikit-project-d541aeb49260">MVVM Binding in UIKit project</a><a href="https://medium.com/@misha.gajdan/unit-testing-in-ios-test-doubles-4be44163470d"><br>Unit Testing in iOS. Test Doubles.</a><a href="https://medium.com/@misha.gajdan/how-to-handle-navigation-in-swiftui-6b04538ab7e"><br>How to handle navigation in SwiftUI<br></a><a href="https://medium.com/@misha.gajdan/handling-multiple-uitableviewcell-s-in-a-viewcontroller-99e197fe0c">Advanced configuration of UITableViewCell-s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b74582828a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM Binding in UIKit project]]></title>
            <link>https://medium.com/@misha.gajdan/mvvm-binding-in-uikit-project-d541aeb49260?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d541aeb49260</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 10:06:59 GMT</pubDate>
            <atom:updated>2023-06-06T12:33:42.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnVS3lGXliuGheFxBzx7uA.png" /></figure><p>As I see for the last few years <em>MVVM</em> it’s one of the most popular design patterns and <em>MVVM</em> commonly used by software engineers.</p><p>In the <em>SwiftUI</em> app, mostly <em>Published</em>, properties are used to implement Bindings, but what about <em>UIKit</em>?<br>The most popular answer is the <a href="https://medium.com/@nimjea/delegation-pattern-in-swift-4-2-f6aca61f4bf5">Delegate</a> pattern and/or <a href="https://docs.swift.org/swift-book/documentation/the-swift-programming-language/closures/">Closures</a>.<br>It may work in most cases, but it has one huge disadvantage. It’s a one-to-one relationship. <br>For example with closures. If you have 2 UI elements, which use the same View Model, and if both of them have to be subscribed to the same closure, only one UI element can listen that event. Let’s see in an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88a9e3d59516954fb55c7b51752d1f48/href">https://medium.com/media/88a9e3d59516954fb55c7b51752d1f48/href</a></iframe><p>The example below is very simple, but it shows the problem.</p><p>In this example we have a View Model, <em>VM</em> and two 2 ui elements/classes, <em>MainUI</em> and <em>SubUIElement</em>.</p><ol><li>Emulates an API call to the server.</li><li>Emulate some UI changes.</li><li>Emulate some UI changes.</li><li>Main render/build function.</li></ol><p>Let’s go to render function:</p><p>5. <em>render</em> function creates a new <em>MainUI</em> object.</p><p>6. <em>fetchData</em> call is made and “Update UI in MainUI: [“a”, “b”, “c”]” is printed.</p><p>7. <em>MainUI</em> object creates an UI element <em>SubUIElement.</em></p><p>8. Another <em>fetchData</em> call is made, but only `Update UI in <strong>SubUIElement</strong>: [“a”, “b”, “c”]` is printed. And here is a problem. <em>Closures</em> nor <em>Delegate pattern</em> doesn’t give possibilities to have one-to-many connection. <br>As an alternative, we may use <a href="https://developer.apple.com/documentation/foundation/nsnotificationcenter">the Observer pattern</a>. But, as <em>ViewModel</em> grows, it’s really hard to maintain and, from my experience, bugs from using <em>NSNotificationCenter</em>, really hard to detect, reproduce and fix.</p><p>So what can we do with it? <a href="https://developer.apple.com/documentation/combine">Combine Framework</a> can help us, particularly <a href="https://developer.apple.com/documentation/combine/passthroughsubject">PassthroughSubject</a> but with a few tweeks. This Subject is really easy to use and doesn’t require deep Combine knowledge.<br>So, what does this Subject do? It simply “sends” an event and subscribers “listen” to it. Kind of similar logic as with closures.</p><p>Let’s replace <em>onChange</em> variable with <em>PassthroughSubject</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f866d8e4fa3dd8e5f9acd8862dab816/href">https://medium.com/media/0f866d8e4fa3dd8e5f9acd8862dab816/href</a></iframe><ol><li>To use <em>PassthroughSubject</em>, we need to import <em>Combine</em> of course.</li><li>We replaced <em>onChanged</em> with <em>onChangedSubject</em>. “<em>Never</em>”, second parameter in subject, means that the subject should not send any errors.</li><li>Both, in <em>MainUI</em> and <em>SubUIElement</em> classes, should use an <em>AnyCancellable</em> variable to store subscriptions (or <em>AnyCancellable</em> Set, as in gist above. Both <em>AnyCancellable</em> variable and Set work nice, but I prefer to use Set :)).</li></ol><p>In both classes we call “<em>sink</em>” closure, to receive value and store subscription in the <em>cancelable</em> Set, by calling <em>cancelable.insert(…)</em>.</p><p>After <em>buildUIElement</em> and <em>fetchData</em> are called, we see both messages: <br>Update UI in MainUI…” and “Update UI in SubUIElement…”</p><p>As <em>PassthroughSubject</em> will be used more commonly, what we can improve is to get rid of the error (“<em>Never”)</em> argument.<br>It can be done by wrapping <em>PassthroughSubject</em> into a custom <em>Subject</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94fff1d573535afca350ba701767ddda/href">https://medium.com/media/94fff1d573535afca350ba701767ddda/href</a></iframe><p>What is done is, that a new class is created, by conforming <a href="https://developer.apple.com/documentation/combine/subject">Subject protocol</a>. In that class <em>Failure</em> was marked as <em>Never</em> and used <em>PassthroughSubject</em> under the hood. New <em>PassSubject</em> will work the same as <em>PassthroughSubject</em>, but now the second, error argument, is not needed.</p><p>Now, View Model looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f4a78450b57ce29b318a6407f14067/href">https://medium.com/media/64f4a78450b57ce29b318a6407f14067/href</a></iframe><p>Now, only the type that will be sent is required. All other code remains the same.<br>But there is one more problem. If you check the code above (line 2 and 3) there are 2 variables. One is to store an Array of String, and another is used to notify UI about changes. And the issue is, that, by mistake, in the function <em>fetchData</em> it’s easy to change the order of calls. Firstly we call <em>onChangedSubject</em> and then save data in <em>arrayOfData</em>, which is incorrect, because <em>onChangedSubject</em> will return an empty array. This bug will be noticed only during runtime.<br>Is this possible to improve? Actually, yes!<br>To fix this another subject is needed, which is called <a href="https://developer.apple.com/documentation/combine/currentvaluesubject">CurrentValueSubject</a>. The difference is, that this subject not only “sends” events, but also stores value.</p><p>Let’s replace <em>PassSubject</em> with a<em>CurrentValueSubject</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86712641141185f670cb2a90343e2ac6/href">https://medium.com/media/86712641141185f670cb2a90343e2ac6/href</a></iframe><ol><li><em>onChangedSubject</em> was removed and Array of Sting was replaced by a <em>CurrentValueSubject</em>.</li><li>Instead of using “<em>arrayOfData”</em>, now need to call “<em>arrayOfData.value”</em> to save a new value (and to access the value, stored in the <em>CurrentValueSubject</em>, also need to use the <em>value</em> property).</li><li>Similarly, need to call “<em>arrayOfData.sink”</em> to receive new values. But one minor update, I used “<em>dropFirst”</em> because every time when you subscribe to <em>CurrentValueSubject</em> for the first time, it sends a value stored in the subject. To avoid this behavior, use “<em>dropFirst”</em> before “<em>sink”</em>.<br>And the last thing is to get rid of the error (“<em>Never</em>”) argument. Similarly as with <em>PassthroughSubject</em>, a new <em>Subject</em> class is required:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96ab4f41f144eee26b478d322e3d9e7a/href">https://medium.com/media/96ab4f41f144eee26b478d322e3d9e7a/href</a></iframe><p>And finally, ViewModel after replacing <em>CurrentValueSubject</em> with <em>ValueSubject:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8f9221b8750b571eb7ca28105cf4bd6/href">https://medium.com/media/d8f9221b8750b571eb7ca28105cf4bd6/href</a></iframe><p>And it’s finished. We moved away from <em>Closures</em> to <em>Subjects</em> with not so signigicat changes. This approach has a lot of benefits: Easy to implement, easy to understand, doesn’t require deep Combine knowledge and allows you to cover your code using unit tests.</p><p>To summarize, when to use <em>ValueSubject</em> and when to use <em>PassSubject</em>:</p><ul><li><em>PassSubject</em> — it’s a good candidate when you are interested in one time event and not interested in storing any data (e.g. need to present an error/message alert from api call).</li><li><em>ValueSubject</em> — when you are interested not only in an event, but also in value (e.d. “<em>dataSource”</em> for “<em>UITableView”</em>, when dataSource is populated from an API).</li></ul><p>That’s all. Hope this article will help you to build robust and flexible <em>MVVM</em> apps. <br>Thank you for reading ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d541aeb49260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing in iOS. Test Doubles.]]></title>
            <link>https://medium.com/@misha.gajdan/unit-testing-in-ios-test-doubles-4be44163470d?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4be44163470d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[apple-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 09:34:57 GMT</pubDate>
            <atom:updated>2024-05-27T10:18:38.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NpdCW7LnoniGToXJ" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Often I see, when iOS developers are writing unit testing for their apps, they use only <em>Mock</em> objects, to simulate responses (it may be server response, Third library response, etc.).</p><p>This approach isn’t so bad, but if we need to use that <em>mock</em> object in different places, it becomes much larger and complex (it may record calls count, save some information, can contain different if — else conditions and so on). Important rules for unit tests that have to be small and simple. <em>Test Doubles</em> will help us to achieve this rule.</p><p>What are <em>Test Doubles</em>? From <a href="https://martinfowler.com/bliki/TestDouble.html">Martin Fowler’s article</a>, (which I highly recommend to read. All next definitions are taken from that article) <em>Test Double</em> is a generic term for any case where you replace a production object for testing purposes.</p><p>Here is a list of possible <em>Test Doubles</em> objects:</p><ul><li>Dummy</li><li>Fake</li><li>Stubs</li><li>Spies</li><li>Mock</li></ul><p>Let’s figure out what are they one by one with examples on <em>Swift</em>:</p><h3>Dummy</h3><p>Objects are passed around but never actually used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/980eb719d443808ce2db048d2c12aee1/href">https://medium.com/media/980eb719d443808ce2db048d2c12aee1/href</a></iframe><h3>Fake</h3><p>Objects actually have working implementations, but usually take some shortcut which makes them not suitable for production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8842f426a5ca3aec6037c846f3f87a73/href">https://medium.com/media/8842f426a5ca3aec6037c846f3f87a73/href</a></iframe><p>As you can see, <em>save</em> and <em>delete </em>methods have similar persistence logic, but we do not depend on <em>CoreData</em> stack. Or, we also may use <em>CoreDataStack</em> implementation, but with type <a href="https://developer.apple.com/documentation/coredata/nsinmemorystoretype">NSInMemoryStoreType</a> for data saving. Instead of local persistence storage we will use <em>RAM </em>memory. Both ways represent <em>Fake Objects.</em></p><h3>Stubs</h3><p>Provide preprogrammed answers to the object owner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25f166c2806ee4869dff472cfc9ef5d/href">https://medium.com/media/d25f166c2806ee4869dff472cfc9ef5d/href</a></iframe><p>As you can see on line 18, we set up a response, which <em>MessageService </em>should send to us<em>. </em>On line 22, Hello world will be printed.</p><h3>Spies</h3><p><em>Stubs</em> that also record some information based on how they were called (e.g. how many times function has been called).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a928003427405498f2ce93e45b87c490/href">https://medium.com/media/a928003427405498f2ce93e45b87c490/href</a></iframe><p><em>Spy</em> objects are most commonly used, because, usually, we are interested in the service response and how many times service’s function has been called (imagine we have Socket service and we need to be sure that connect function has been called just once, not multiple times).</p><h3>Mock</h3><p>Objects pre-programmed with expectations which form a specification of the calls they are expected to receive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38d6cf40ca04e8c034d8adb528d9a9b/href">https://medium.com/media/b38d6cf40ca04e8c034d8adb528d9a9b/href</a></iframe><p>But, as for me, I prefer to use the Stub object, because we don’t need to go into implementation details and we can set expectations in the body of the test function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3175ad6269b0264052c534fae66978e5/href">https://medium.com/media/3175ad6269b0264052c534fae66978e5/href</a></iframe><p>One note. You may notice that I used an unwrapped Bool. It’s ok for unit tests (even useful), because if our test will crash, we can easily find missed configuration of the stub object (from my experience pre configured properties slow down writing because you may simply forget about pre configured values and you need to dive deep into implementations details to understand why unit test doesn’t work).</p><p>I hope this article was helpful and <em>Test Doubles </em>will<em> </em>help you to write clean and understandable tests.</p><p>Thank you for reading ❤️.</p><p>Check out my other articles:</p><p><a href="https://medium.com/@misha.gajdan/how-to-handle-navigation-in-swiftui-6b04538ab7e">How to handle navigation in SwiftUI</a><br><a href="https://medium.com/@misha.gajdan/handling-multiple-uitableviewcell-s-in-a-viewcontroller-99e197fe0c">Advanced configuration of UITableViewCell-s</a><br><a href="https://medium.com/@misha.gajdan/how-to-handle-navigation-in-swiftui-6b04538ab7e">How to handle navigation in SwiftUI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4be44163470d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a UIKit user interface programmatically. Tips & suggestions.]]></title>
            <link>https://medium.com/@misha.gajdan/tips-and-suggestions-of-build-ui-in-code-398b415f228a?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/398b415f228a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Sun, 19 Sep 2021 11:47:31 GMT</pubDate>
            <atom:updated>2021-09-19T14:38:01.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zztiMcnaauL7lAnwz5qjoA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio">Charles Deluvio</a><strong> </strong>on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>I’ve been building a UI in code for 2 years and I’d like to share my suggestions and tips with you, which I’ve figured out during this period.</p><h3>1. Use <a href="https://github.com/SnapKit/SnapKit">SnapKit</a> instead of <a href="https://developer.apple.com/documentation/uikit/nslayoutconstraint">NSLayoutconstraint</a>/<a href="https://developer.apple.com/documentation/uikit/nslayoutanchor">NSLayoutAnchor</a>.</h3><p>It’s hard and time-consuming to set up constraints in code, using <em>NSLayoutconstraint-s</em>, then in iOS 9, were announced <em>NSLayoutAnchor-s. </em>What simplifies settings up.</p><p>Even if <em>NSLayoutAnchor-s </em>give a really nice API, still, it requires a lot of time to set up all constraints, that is why I suggest to use <em>SnapKit</em> instead.</p><p>Let’s compare these both<em>, </em>starting from <em>NSLayoutAnchor:</em></p><pre>subView.translatesAutoresizingMaskIntoConstraints = <strong>false</strong></pre><pre>NSLayoutConstraint.activate([<br>  subView.topAnchor.constraint(equalTo: view.topAnchor),<br>  subView.leadingAnchor.constraint(equalTo: view.leadingAnchor),<br>  subView.trailingAnchor.constraint(equalTo: view.trailingAnchor),<br>  subView.bottomAnchor.constraint(equalTo: view.bottomAnchor)<br>])</pre><p>And similar code using <em>SnapKit</em>:</p><pre>subView.snp.makeConstraints { make in<br>  make.edges.equalToSuperview()<br>}</pre><p>There is a significant difference in the amount of the code, easy to set up and understand. That’s why I highly recommend using <em>SnapKit DSL</em>.</p><h3>2. Use USStackView as <strong>frequently</strong> as possible.</h3><p>This one is obvious, but worth mentioning. Even though it’s easy to set up constraints using <em>SnapKit</em>, it’s always better to not use them at all.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7bf83f883b1cb8a6d0832f53efe7d10/href">https://medium.com/media/a7bf83f883b1cb8a6d0832f53efe7d10/href</a></iframe><p>And similar result without <em>UIStackView:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b5f9cb0e37d8a234f03422866987406/href">https://medium.com/media/9b5f9cb0e37d8a234f03422866987406/href</a></iframe><p>Now the setup method is much harder to understand. Compared to <em>UIStackView, </em>where we need to set up only it’s constraints and everything else <em>UIStackView</em> has done for us.</p><h3>3. Do not build UI in a UIViewController, but create a subview instead.</h3><p>Even if we use <em>SnapKit</em> or <em>UIStackView</em>, usually we need a lot of code to build an UI and often we do this directly in the body of a <em>UIViewController</em>. Because of the specification of iOS apps, <em>UIViewController </em>may<em> </em>also contain some services/configurations (especially if we use MVC architecture). As result we will get huge <em>UIViewController </em>and, additionally, nightmare merge requests, if more then one developer is working on the same screen (what I had, when one developer was working on UI and I was updating the logic)<em>.</em></p><p>Instead of this approach, we can create a custom <em>UIView </em>and override <em>loadView </em>function and set the view in the body of that function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e2bc85d1febcb37024a4980a26681c5/href">https://medium.com/media/9e2bc85d1febcb37024a4980a26681c5/href</a></iframe><p>Our <em>self.view </em>is a <em>CustomView </em>and all UI configuration is now encapsulated inside <em>CustomView. </em>Now our <em>UIViewController</em>-s are much smaller.</p><h3>4. Use <a href="https://docs.swift.org/swift-book/LanguageGuide/Properties.html"><em>Lazy Stored Properties</em></a> for a subview and add the subview in the body of lazy var<em>.</em></h3><p>It’s not so obvious why we need to use <em>lazy var</em>-s and why it is so important to add a subview in the body of it, instead of doing this in one setup method.</p><p>Let me show you in this example, starting from one setup method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c113f697a0e2ed89416f0185a28c6fa/href">https://medium.com/media/4c113f697a0e2ed89416f0185a28c6fa/href</a></iframe><p>Looks ok, but what if we need to redesign our component and we move the setup of <em>subtitleLabel</em>above <em>titleLabel</em>? Of course we will get this crash, because we pinned <em>titleLabel to subtitleLabel (</em>see line 27 from previous listing<em>)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1ODe7iYNenFJiHxWz9rpw.png" /></figure><p>You may suggest, simply don’t put <em>subtitleLabel</em><strong> </strong>above and it’s valid point :)<br><strong>But</strong>, in the real world, there may be 10–15 different properties, with different configurations, some of them may appear for a specific state and you’ll notice this issue only at runtime. And here comes <em>Lazy Property to </em>help us. Refactor the code using them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ee710e7c3af3a2cade41eb9c5a6a8ee/href">https://medium.com/media/9ee710e7c3af3a2cade41eb9c5a6a8ee/href</a></iframe><p>Now if we move <em>subtitleLabel</em> above, everything works, because properties are initialized and added as subview only when they are called explicitly, so when we configure constraints, a subview already will be added to it’s parent.</p><p>It is a very basic example, but it also works for much more complex views as well.</p><h3>5. Setup UI elements in top/bottom manner.</h3><p>It’s a really bad idea to set up properties of your view in chaotic order. You may understand how it works now, but after months, if some updates are needed, you need to relaunch your app again and again to understand the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*Wcss9R2a-be-jnd4vI99vw.png" /></figure><p>Instead configure UI from the top to the bottom, so, as you see the components — in the same manner you see the code. Now it’s much easier to understand/read the code and imagine the UI “in mind”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*f9Qp-cuGqUzUoWuk5XeOjA.png" /></figure><h3>6. Use SwiftUI Preview.</h3><p>It’s possible to use preview not only for <em>SwiftUI</em>, but for <em>UIKit</em> as well!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac14fce5238804beedb65b9c350c913d/href">https://medium.com/media/ac14fce5238804beedb65b9c350c913d/href</a></iframe><p>Check out this <a href="https://medium.com/swlh/how-to-use-live-previews-in-uikit-204f028df3a9">amazing article</a> for more details.</p><p>Hope this article was useful to you. <br>Thank you for reading ❤️.</p><p>Check out my other articles:</p><p><a href="https://medium.com/@misha.gajdan/how-to-handle-navigation-in-swiftui-6b04538ab7e">How to handle navigation in SwiftUI</a><br><a href="https://medium.com/@misha.gajdan/handling-multiple-uitableviewcell-s-in-a-viewcontroller-99e197fe0c">Advanced configuration of UITableViewCell-s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398b415f228a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced configuration of UITableViewCell-s]]></title>
            <link>https://medium.com/@misha.gajdan/handling-multiple-uitableviewcell-s-in-a-viewcontroller-99e197fe0c?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/99e197fe0c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uitableviewcell]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 12:02:59 GMT</pubDate>
            <atom:updated>2021-09-13T06:42:35.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-osuF59OHrOhyjCpbYqqA.png" /><figcaption>Image from <a href="https://developer.apple.com/documentation/uikit/uitableview">UITableView documentation</a></figcaption></figure><p>How often do you write/see code like this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa734caa30e3915a25147f79577a658/href">https://medium.com/media/bfa734caa30e3915a25147f79577a658/href</a></iframe><p>I don’t like such setup because it breaks <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">Open-close principle</a> and, if we have a really complex structure we will get an endless list of <em>if-else</em> conditions. In the end it’s really hard to control.</p><p>I’d like to propose an approach, which I’m using almost for every <em>UITableView </em>component.</p><p><strong>I’ll describe it with a simple example.</strong></p><p>First, let’s get started with a usual <em>UITableView</em> setup. Assume, that we have a <em>Profile</em> screen with following components:</p><ul><li>First name and last name</li><li>Profile Image</li><li>Bio</li></ul><p>The prototype result may looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*_hrF63f3dFEKDJh77ceCUg.png" /></figure><p>And <em>Profile</em> model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce07f20fb0247690040f08ecd52c6046/href">https://medium.com/media/ce07f20fb0247690040f08ecd52c6046/href</a></iframe><p>As usual, we will create 3 cells (the source code is attached to each name):</p><ul><li><a href="https://gist.github.com/mikehaydan/5c741b409f858eb9065c4e1c19219a9f"><em>NameTableViewCell</em></a></li><li><a href="https://gist.github.com/mikehaydan/dd2ebf5445085ffd03085c3c9e00e739"><em>ImageTableViewCell</em></a></li><li><a href="https://gist.github.com/mikehaydan/f2eb7456d2b9d04ae8f94019833fcd60"><em>BioTableViewCell</em></a></li></ul><p>Each cell accepts <em>Profile</em> model as a parameter, so cells have such function:</p><pre>func setup(with profile: Profile) { <br>     ... <br>}</pre><p>And our final <em>TableView</em> setup looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22188eabf1de1402fc830d05de07d8aa/href">https://medium.com/media/22188eabf1de1402fc830d05de07d8aa/href</a></iframe><p>Listing of the <em>ViewController </em>can<em> </em>be found <a href="https://gist.github.com/mikehaydan/f32fd0720f9894e4242f312bb5612186">here</a>.</p><p>What I can say about this implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*srA1zEEh-oI97sCVrvtQQw.jpeg" /><figcaption>Image from <a href="https://www.hbo.com/chernobyl">Chernobyl TV series</a></figcaption></figure><p>This approach may work, but what if we need to add a new item, we will get a new <em>case</em> block. Also we can forget to update a number of the items and so on…</p><p><strong>Let’s try in another way!</strong></p><p>First let’s add a <em>Protocol.</em></p><pre><strong>protocol</strong> ReusableItem {<br>    <strong>var</strong> reuseIdentifier: String { <strong>get</strong> }<br>}</pre><p>It simply has one computed property, which will return a <em>reuseIdentifier </em>of custom <em>UITableViewCell.</em></p><p>Now, we will create an Abstract <em>UITableViewCell.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9391f950fb72d3b87e8bb5219853cf96/href">https://medium.com/media/9391f950fb72d3b87e8bb5219853cf96/href</a></iframe><p>Pretty simple. We have just one method, which accepts <em>ReusableItem </em>and which has to be overridden by it’s child.</p><p>Now, we need to create models that represent each cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a71a73f04986b3717e8095f0123841/href">https://medium.com/media/38a71a73f04986b3717e8095f0123841/href</a></iframe><ol><li>Implementation of <em>ReusableItem </em>protocol. Each model returns a reusable identifier of it’s <em>UITableViewCell.</em></li><li>Params, which are necessary for specific <em>UITableViewCell.</em></li></ol><p>Now, we will add one helper property to our <em>Profile</em> model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6a6c51a57e5f394bc86bc15247e2cf2/href">https://medium.com/media/d6a6c51a57e5f394bc86bc15247e2cf2/href</a></iframe><p>This computed property transforms the Profile<em> </em>model to an array of <em>ReusableItem</em>s.</p><p>Next, each cell has to inherit from <em>BaseReusableTableViewCell </em>and implement “<em>func setup(with model: ReusableItem)”</em> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8f6fba19ed0c168c76504c3a7ea29c/href">https://medium.com/media/fb8f6fba19ed0c168c76504c3a7ea29c/href</a></iframe><ol><li>We can cast to “Cell” model using <em>force unwrap </em>without any doubts, because each model represents it’s own cell.</li><li>Setting up cells properties.</li></ol><p>And final updates in the <em>ViewController.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9d8feaa19215d8c8580f9a956a93df4/href">https://medium.com/media/e9d8feaa19215d8c8580f9a956a93df4/href</a></iframe><ol><li>Instead of using profile directly, <em>dataSource </em>has been added, which we will use for <em>UITableViewDataSource.</em></li><li>Settings up <em>dataSource</em>, using computed property from <em>Profile, </em>which has been added recently.</li><li>As you can see, the <em>switch </em>has been replaced by a few lines of code. No matter how many components we have in Profile, the implementation won’t be affected.</li><li>Instead of “hard coded” value, <em>dataSource.count </em>is used. Now we don’t care about the number of items for <em>UITableView</em>.</li></ol><p><strong>And that’s it! Implementation is done. What benefits it has:</strong></p><ul><li>We can easily rearrange, remove, add new items. <em>UIViewController </em>stays untouchable.</li><li>No matter how complex the <em>UI</em> is, the setup is always the same.</li><li>We can write unit tests for data source setup! Because setup has been removed from the <em>ViewController</em> and moved to the model instead (In real world it can be moved to <em>Presenter</em> or <em>ViewModel</em>).</li><li>We can easily reuse cells, because they are specific to their own data.</li><li>This appraoch really easy to implement!</li></ul><p>Hope this article will help build much flexible <em>UITableView.</em></p><p>Thank you for reading ❤️.</p><p>Full implementation you can find <a href="https://github.com/mikehaydan/UITableViewCells-Handling">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99e197fe0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to handle navigation in SwiftUI]]></title>
            <link>https://medium.com/@misha.gajdan/how-to-handle-navigation-in-swiftui-6b04538ab7e?source=rss-c93db64c02c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b04538ab7e</guid>
            <category><![CDATA[mvvm-c]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mike Haidan]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 15:05:08 GMT</pubDate>
            <atom:updated>2021-10-15T08:17:58.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRayLMdg-MS8BHZbt5sinA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alex_andrews">Alexander Andrews</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>The 3rd version of <em>SwiftUI</em> has been released and we still don’t have an answer. How to remove navigation from the UI layer?</p><p>If you tried any complex navigation in <em>SwiftUI</em>, you may noticed, that navigation is “tightly tied” in the <em>UI</em> layer, what brings these problems:</p><ul><li>Blurred boundaries between <em>logic</em> and <em>UI.</em></li><li>Dynamic navigation issues. Building navigation when an order of the screens depends on different factors (A/B tests, configuration flows, etc.).</li></ul><p>I tried different ways to handle navigation in <em>SwiftUI</em> (there are some great articles about navigation in <em>SwiftUI</em>. I highly recommend <a href="https://quickbirdstudios.com/blog/coordinator-pattern-in-swiftui/"><strong>this one</strong></a>), but, unfortunately, all approaches are faced with basic <em>SwiftUI</em> this principles, you need to add <em>NavigationLink </em>explicitly<em> </em>in the <em>UI</em> code!</p><p>This approach adds endless<em> if-else</em> conditions or Boolean properties (or usually both!).</p><p>That brings us to the sad truth, need to use <strong><em>UIKit</em>.</strong></p><p><strong>BUT, </strong>at the end, it’s not so sad, as it sounds. This problem gave an opportunity to build something really flexible. Navigation, using <em>UIKit</em>, but still using <em>SwiftUI</em> under the hood.</p><p>Let’s get started! As app architecture was decided to use MVVM+Coordinator pattern. It works really well in the <em>SwiftUI </em>ecosystem. (I won’t describe the Coordinator pattern in the article. There are a lot of amazing articles already :) ).</p><p><strong>Let’s start from <em>Coordinator</em> protocol:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa726627c32b8a29cfc59cd29d053833/href">https://medium.com/media/fa726627c32b8a29cfc59cd29d053833/href</a></iframe><ol><li>Child coordinators of “<em>self</em>”. The array is not empty, if the <em>Coordinator</em> has children.</li><li>Parent coordinator of “<em>self</em>”. The property is not <em>nil</em>, if the <em>Coordinator</em> has a parent.</li><li>Root controller of the <em>Coordinator</em> (e.g. it may be <em>UINavigationController</em>, <em>UITabBarController</em>).</li></ol><p><strong>Let’s got to the <em>ViewModel</em>:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a8862ba47722efcdfeb57fdcd84045f/href">https://medium.com/media/0a8862ba47722efcdfeb57fdcd84045f/href</a></iframe><ol><li><em>ViewModel</em>’s coordinator. Each <em>ViewModel</em> has to have a link to a <em>Coordinator.</em></li><li>Setup method, where we are making some initial setup (e.g. API calls, data source setup, etc.).</li></ol><p><strong>And <em>View</em> itself:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c54fc46a4b346810ddad0f6f552aed15/href">https://medium.com/media/c54fc46a4b346810ddad0f6f552aed15/href</a></iframe><ol><li>Initialization method for a <em>View</em>. Mostly, it should take only <em>ViewModel</em> as a parameter.</li><li>A computed property, which transforms a <em>View</em> to a <em>UIViewController </em>(it may be <em>UIHostingViewController</em> for <em>SwiftUI.View</em>).</li></ol><p><strong>And final component, a view controller wrapper</strong> (it has been developed as abstract class, so each view has to have it’s own implementation):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36f645bf0a0e2bd01ef03a8ec8d5584f/href">https://medium.com/media/36f645bf0a0e2bd01ef03a8ec8d5584f/href</a></iframe><ol><li>strong reference<em> </em>to a <em>ViewModel.</em> Note: <em>SwiftUI.View</em> has to have @<em>ObservedObject </em>wrapper instead of <em>@StateObject.</em></li><li>Represents a <em>View</em>, transformed to a <em>UIView</em> object.</li><li>It’s not allowed to create an instance of <em>SwiftUIViewController, </em>but need to inherit it instead (an example will be later in the article).</li><li>Adding a <em>View </em>as a child <em>UIViewController </em>and pinning it to the edges, using<em> NSLayoutConstraint.</em></li></ol><p>And that’s it. Our setup is ready. By confirming these protocols we can develop a UI using <em>SwiftUI</em> and wrap it into a <em>UIViewController</em> and it’s almost done.</p><p><strong>The final result looks like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e80ba249e78eb77e7e01cc7994ee819/href">https://medium.com/media/4e80ba249e78eb77e7e01cc7994ee819/href</a></iframe><p>Our final controller is on line 75. As you can seen we don’t need to do any configurations. Everything has been done under the hood. Usually <em>UIViewController</em> should only few lines of code.</p><p>You may ask why not to use <em>UIHostingController </em>directly? <br>There are couple of reasons:</p><ul><li>A <em>View</em> has all <em>UIViewController</em> lifecycle methods, which add a more flexible setup.</li><li>This approach forces a developer to use <em>MVVM+C</em> architecture.</li><li>And the most useful reason, if you’re unable to develop something in <em>SwiftUI</em>, you can easily switch to <em>UIKit</em>. <em>ViewControllerView </em>protocol doesn’t require using <em>SwiftUI.</em> <em>UIViewController </em>can<em> </em>implement <em>ViewControllerView </em>as well. All other components stay untouched.</li></ul><p>Regarding last point, here is an example how easy we can switch between <em>SwiftUI</em> and <em>UIKit:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50df06cbea2071609532bc5c5266fe32/href">https://medium.com/media/50df06cbea2071609532bc5c5266fe32/href</a></iframe><p>That’s all! I know this approach is not a silver bullet to solve all issues in <em>SwiftUI</em>, but it adds some flexibility and safety of build our apps.</p><p>Thank you for reading ❤️.</p><p>More detailed implementation you can find <a href="https://github.com/mikehaydan/swiftUI-uikit">here</a>.</p><p>Check out my other articles:</p><p><a href="https://medium.com/@misha.gajdan/tips-and-suggestions-of-build-ui-in-code-398b415f228a">Building a UIKit user interface programmatically. Tips &amp; suggestions.</a><br><a href="https://medium.com/@misha.gajdan/handling-multiple-uitableviewcell-s-in-a-viewcontroller-99e197fe0c">Advanced configuration of UITableViewCell-s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b04538ab7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>