<?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 Maxim Krylov on Medium]]></title>
        <description><![CDATA[Stories by Maxim Krylov on Medium]]></description>
        <link>https://medium.com/@maxim-kryloff?source=rss-12dd38bd5bf5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7WOfx1EN2oj3r-1LcGYxLw@2x.jpeg</url>
            <title>Stories by Maxim Krylov on Medium</title>
            <link>https://medium.com/@maxim-kryloff?source=rss-12dd38bd5bf5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:01:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxim-kryloff/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[Swift. Packages and Bundles. Resources]]></title>
            <link>https://maxim-kryloff.medium.com/swift-packages-and-bundles-resources-82f06c66b19e?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f06c66b19e</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sat, 29 May 2021 16:28:23 GMT</pubDate>
            <atom:updated>2021-05-31T07:44:40.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p>Before reading the text below, take a look at <a href="https://medium.com/@maxim.kryloff/swift-static-and-dynamic-libraries-frameworks-343952d3011e">this</a></p><p>The current work is a continuation of discussions about libraries, frameworks, and executables</p><p>After reading <a href="https://medium.com/@maxim.kryloff/swift-static-and-dynamic-libraries-frameworks-343952d3011e">the article</a>, you may question: where are frameworks located in a device before loading into physical memory by the dynamic loader?</p><p><a href="https://medium.com/@maxim.kryloff/swift-static-and-dynamic-libraries-frameworks-343952d3011e">The article</a> said that app and library code is transformed into the executable binary file, and that file represents your app. But the binary itself is just a set of instructions for a processor. And what about resources like images, nibs, or localized strings? Where are they?</p><p>Frameworks have their own resources, and moreover, they (frameworks) are not embedded into the resulting binary because of dynamic linkage. So, we have to take a framework at runtime and load it into RAM. What is the place we should go for it?</p><p>The simple answer is: any app is a package (or a particular type of bundle) that stores frameworks, separate dynamic libraries provided by Xcode, the result executable binary, files with app metadata, resources, etc. And what you see on your iPhone isn’t a binary but a directory with everything needed inside</p><p>So, let’s take a look at bundles, packages, and resources a bit closer to have a full picture of how it works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VZz3hlCraNhy9d5G8ubxA.png" /></figure><p>A bundle can be a package, but not any package can be a bundle because a package can have any folder structure inside, and bundles themselves have standardized structures</p><p>Xcode automatically creates bundle structure for the following targets: application, framework, plug-in. Shell scripts, static libraries, and separate dynamic libraries (not a framework) don’t use a bundle structure</p><p>Due to a bundle is just a folder, you can create it manually. No magic here. Create a folder, add correct folder extension depends on the type, meet all requirements of the structure, and that is it!</p><p>Bundle structures of frameworks, applications, and plug-ins can vary depending on macOS and iOS accordingly. In this article, we <strong>mainly refer to iOS</strong></p><p>Let’s take a look at the structure of the most popular bundle types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myhOA_tH9Ruaus_IuKz4lw.png" /></figure><p>The structures of different bundle types are pretty similar</p><p>The *.lproj folders store images, sounds, strings, etc., that are used for chosen app language. It’s easy to use localized resources just out of the box. All you need is to put your resources in the correct lproj folder</p><p>Info.plist has bundle configuration information, e.g. CFBundleIdentifier — is a unique bundle identifier</p><p>In iOS, bundle resources are located in the top-level folder (in macOS, bundles store resources in the Resources folder). You can also create your own folder and put there any resources or files you want. The only requirement — the folder shouldn’t be called “Resources” :)</p><p>Just a few words about an Assets.car problem. Your project can store some resources in the Assets.xcassets folder. It’s a pretty comfortable way to keep images of different sizes. After building, the application bundle will contain a file with the .car extension. That file is a compiled version of the Assets.xcassets folder. Your images and other resources from the Assets.xcassets folder will be stored there</p><p>Let’s say you have a module that has its own Assets.xcassets folder, as a result — its own Assets.car file. If you want to build your module as a <strong>static library,</strong> you can catch a conflict that will say: “I have the Assets.car file from your module and the same file from the application. I don’t know what to do…” Until resolving the conflict, you won’t be able to build your app</p><p>The possible solution is to create a custom bundle package (plug-in) for each module and store resources there (like in the picture above). So, your modules will store their Assets.car files inside such packages</p><p>Here are several facts about module resources:</p><ul><li>If you build your module as a static library, its code will be embedded into the result executable binary, and its resources (images, plug-ins, strings, .car files, …) will be placed in the application bundle, in the top-level folder</li><li>If you build your module as a framework, its resources will be placed in its own .framework bundle folder (as a result, no conflicts with the Assets.car file; yep, it is the second possible solution of the Assets.car problem — using frameworks over static libraries)</li></ul><p>Again, an application bundle is that guy you interact on your iPhone with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6AfesUAzfzTAqaRfZ-fzg.png" /></figure><p>And finally, here are several examples of how to work with bundles in code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0IquCw19RIuthoKD7UhkFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lR-cSu4ANo38iQGIZrzkg.png" /></figure><h3>Resources</h3><ul><li><a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i-CH1-SW1">https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/Introduction/Introduction.html#//apple_ref/doc/uid/10000123i-CH1-SW1</a></li><li><a href="https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Frameworks.html#//apple_ref/doc/uid/10000183-SW1">https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Frameworks.html#//apple_ref/doc/uid/10000183-SW1</a></li><li><a href="https://blog.timac.org/2018/1018-reverse-engineering-the-car-file-format/">https://blog.timac.org/2018/1018-reverse-engineering-the-car-file-format/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f06c66b19e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Static and Dynamic Libraries. Frameworks]]></title>
            <link>https://maxim-kryloff.medium.com/swift-static-and-dynamic-libraries-frameworks-343952d3011e?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/343952d3011e</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Thu, 20 May 2021 08:14:33 GMT</pubDate>
            <atom:updated>2021-05-30T09:59:25.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p>There are a lot of articles that tell about libraries and frameworks in Swift. At the bottom of this page, you will find links to materials I highly recommend to get acquainted with</p><p>The goal of my work isn’t to produce one more article that tells the same as dozens before. Even more, most of them are really great!</p><p>In this article, I tried to visualize the process of compiling, linking, and simply working with libraries and frameworks. I hope this work will be a good extension of materials you can find all over the Internet and in the Apple documentation</p><p>Well, let’s get started with the types of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSmd-E6tYwi-LmTLWd4bsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keUBt03gzTWeaFxgP8sJqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQDnFO9SEaYUYjX4eBTNTQ.png" /></figure><p>Static libraries are fully embedded into the result executable binary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMHoDitG4Fa7AKMaR2Pvcw.png" /></figure><p>Dynamic ones behave differently. The result executable binary has just references to the functions of that libraries. And the code of the functions is loaded at runtime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWAwVF6imBWjigWderUnFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zw_eLq5YF_zrFfSA5qEVxA.png" /></figure><p>Let’s take a look at what Xcode and iPhone do under the hood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjunwNjuMv3wCzBma9OXPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDHWpUDNrZ3rsyc1pMqPTA.png" /></figure><p>And now let’s see what frameworks are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiWdxboNhQMeL0ZGmnKfyg.png" /></figure><p>To summarize everything above, let’s say that in <strong>iOS</strong>/macOS development, there are two types of modules:</p><ul><li><strong>library</strong>, and its synonyms like a static library, static framework</li><li><strong>framework</strong>, and its synonyms like a dynamic framework</li></ul><p>Telling about <strong>libraries</strong> or static frameworks, people assume <strong>static</strong> libraries — modules, that are fully embedded into the result executable binary</p><p>And speaking about <strong>frameworks</strong>, they refer to <strong>dynamic</strong> libraries that are wrapped by frameworks and linked to the executable binary via references to their functions</p><p>There are several helpful terminal commands that allow you to determine the type of binary and get some useful information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*487LA_jWSoojYMsGKjCpmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgwfBvmvR32ut0SheFwv6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWjgw-iKAXoP8anCbkI2QQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbNmEK7R5G9AqgrgolBMTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgbOuI03i9DmcN_EDvIWPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*trlDbuQTxN9X8QxEaawtGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LvcOutmJ6ra29wPzOXtWA.png" /></figure><p>In our project, we use cocoapods as Swift dependency manager. As a bonus, let’s see how Xcode treats its dependencies and how they are transformed into static libraries or dynamic frameworks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NA-1CyzorWLjjjaMftEfWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbSCQ55eE_EBMdfXZI9XmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZeVOR3ELfBb_7bOQwsbHQ.png" /></figure><p>I hope it will help you to get closer to the Swift and iOS development and to have a better understanding of not so simple topic :)</p><p><a href="https://maxim-kryloff.medium.com/swift-packages-and-bundles-resources-82f06c66b19e">Here</a> is the second part of this work, where we will discuss bundles and packages. It should give you a more comprehensive picture of what apps are</p><h3>Resources</h3><ul><li><a href="https://www.vadimbulavin.com/static-dynamic-frameworks-and-libraries/">https://www.vadimbulavin.com/static-dynamic-frameworks-and-libraries/</a></li><li><a href="https://www.vadimbulavin.com/xcode-build-system/">https://www.vadimbulavin.com/xcode-build-system/</a></li><li><a href="https://medium.com/@zippicoder/libraries-frameworks-swift-packages-whats-the-difference-764f371444cd">https://medium.com/@zippicoder/libraries-frameworks-swift-packages-whats-the-difference-764f371444cd</a></li><li><a href="https://medium.com/joshtastic-blog/frameworks-and-libraries-in-swift-2359e4274faa">https://medium.com/joshtastic-blog/frameworks-and-libraries-in-swift-2359e4274faa</a></li><li><a href="https://gist.github.com/SheldonWangRJT/78c9bd3b98488487c59a6a4a9c35162c">https://gist.github.com/SheldonWangRJT/78c9bd3b98488487c59a6a4a9c35162c</a></li><li><a href="https://stackoverflow.com/questions/13082149/in-xcode-project-target-build-settings-what-is-mach-o-type">https://stackoverflow.com/questions/13082149/in-xcode-project-target-build-settings-what-is-mach-o-type</a></li><li><a href="https://medium.com/tokopedia-engineering/a-curious-case-of-mach-o-executable-26d5ecadd995">https://medium.com/tokopedia-engineering/a-curious-case-of-mach-o-executable-26d5ecadd995</a></li><li><a href="https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html#//apple_ref/doc/uid/TP40001873-SW1">https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/OverviewOfDynamicLibraries.html#//apple_ref/doc/uid/TP40001873-SW1</a></li><li><a href="https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple_ref/doc/uid/20002303-BBCEIJFI">https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/WhatAreFrameworks.html#//apple_ref/doc/uid/20002303-BBCEIJFI</a></li><li><a href="https://www.objc.io/issues/6-build-tools/mach-o-executables/">https://www.objc.io/issues/6-build-tools/mach-o-executables/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=343952d3011e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code Principles]]></title>
            <link>https://maxim-kryloff.medium.com/clean-code-principles-4c8f665b6cdd?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c8f665b6cdd</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 07:51:19 GMT</pubDate>
            <atom:updated>2020-12-01T18:44:22.270Z</atom:updated>
            <content:encoded><![CDATA[<p><em>It’s so hard and useless to write clean code from scratch. First, make your code work. Then cover it with tests. Your team gets time to test your code, and you have a space to make it clean</em></p><p><em>Clean code is a result of the refactoring</em></p><h3>Functions</h3><p><strong>Principle 1</strong>.<strong> </strong>A name of a function should tell what it does without looking at the implementation</p><pre>// <strong>It is a real function name from the project I participated in<br></strong>func checkNoMovementDuringAction(<br>    element: Element,<br>    action: () -&gt; Void<br>)<br>// <strong>What is the movement?</strong><br>// <strong>And what happens if that movement occurs? I&#39;d suggest a bool<br></strong>//<strong> Why do we need an element here? Is it about the movement?</strong></pre><pre>// <strong>Let&#39;s rename it<br></strong>func doActionAndThrowErrorIfElementPositionIsChanged(<br>    action: () -&gt; Void,<br>    element: Element<br>)<br>// <strong>Well, now the name answers all questions above,<br></strong>//<strong> but it&#39;s quite long, right?<br></strong>// <strong>And it tells implementations details like error throwing,</strong><br>// <strong>which is not good</strong></pre><pre>// <strong>Let&#39;s change its name again</strong><br>func doActionAndEnsureElementPositionNotChanged(<br>    action: () -&gt; Void,<br>    element: Element<br>)<br>// <strong>I think this variant is appropriate</strong><br>// <strong>It&#39;s a kind of compromise between expressiveness and length<br></strong>// <strong>&#39;ensure&#39; describes things better than &#39;check&#39; in this case<br></strong>// <strong>And the name is abstract enough</strong></pre><p><strong>Principle 2</strong>. Any function should be responsible for just one thing. If a function has two responsibilities, its name should reflect both. If it has three or more responsibilities — it’s a bad function</p><p><em>It’s also worth to mention that name of any function should tell about all side effects inside</em></p><p><strong>Principle 3</strong>. ‘Action’ is a function that changes a state of a system and never returns a value. ‘Function’ is a function that returns a value and never changes a state of a system. A function shouldn’t be ‘Action’ and ‘Function’ at the same time</p><pre>let result = accountRepository.update(account)<br>// <strong>What is the result? .success? updatedAccount? Both?<br></strong>// <strong>And what if I don&#39;t need anything but just updating?</strong></pre><pre>// <strong>I tried to refactor<br></strong>accountRepository.update(account)<br>let updatedAccount = accountRepository.getBy(id: account.id)</pre><pre><strong>...</strong></pre><pre>// <strong>However, the worst thing is when you expect the function</strong><br>// <strong>just to return a value, but inside it updates the database</strong><br>let accounts = accountService.createAccountsFrom(accountDTOs)<br>// <strong>createAccountsFrom uses accountRepository to save accounts</strong></pre><pre>// <strong>I would suggest the following</strong><br>let accounts = accountService.createAccountsFrom(accountDTOs)<br>accountService.saveAccounts(accounts)</pre><pre>// <strong>Or even rename &#39;create&#39; to &#39;build&#39; to avoid possible confusions</strong><br>let accounts = accountService.<strong>build</strong>AccountsFrom(accountDTOs)<br>accountsService.saveAccounts(accounts)</pre><pre>// <strong>And one more piece of refactoring here ;)<br></strong>let accounts = account<strong>Factory</strong>.buildAccountsFrom(accountDTOs)<br>account<strong>Service</strong>.saveAccounts(accounts)<br>// <strong>... perfect</strong></pre><p><strong>Principle 4</strong>. There are no function parameters — perfect! Just one parameter — fine! Two parameters — well, it’s still okay. Three and more parameters — if your domain doesn’t tell that is right, it’s wrong</p><p><em>When it has a small number of parameters:</em></p><ul><li><em>Tests become easier</em></li><li><em>It doesn’t take many pieces of knowledge to use</em></li><li><em>It gets simpler to understand how it works</em></li></ul><p><strong>Principle 5</strong>. All rows in a particular function should belong to the same level of abstraction</p><p><em>It is one of my favorite principles :) Just look at the example below</em></p><pre>// <strong>Bad</strong><br>func start() {<br>    initializeResources()<br>    <strong>let topics = getTopicsFrom(config)<br>    for topic in topics {<br>        consumer.subscribe(topic: topic, fromBeginning: true)<br>    }<br></strong>    runKafkaConsumer()<br><strong>    let logBody = [<br>        &quot;tenantAlias&quot;: getTenantAlias(),<br>        &quot;consumerGroup&quot;: getConsumerGroup(),<br>        &quot;kafkaHost&quot;: config.kafkaHost,<br>        &quot;cluster&quot;: config.cluster,<br>        &quot;deploymentType&quot;: config.deploymentType,<br>    ]<br>    logger.info(logBody)</strong><br>}</pre><pre>// <strong>Good<br></strong>func start() {<br>    initializeResources()<br>    <strong>subscribeToTopicsFromConfig()<br>    </strong>runKafkaConsumer()<br>    <strong>logKafkaConsumerStarted()</strong><br>}</pre><p><strong>Principle 6</strong>. All rows in a particular function should follow the same convention</p><pre>// <strong>Bad</strong><br>func loadView() {<br>    createSegmentedControlView()<br>    <strong>self.tableView = </strong>createTableView()<br>    createRootView(<strong>self.segmentedControlView, self.tableView</strong>)<br>}</pre><pre>// <strong>Good<br></strong>func loadView() {<br>    self.segmentedControlView = createSegmentedControlView()<br>    self.tableView = createTableView()<br>    self.view = createRootView(<br>        segmentedControlView: self.segmentedControlView,<br>        tableView: self.tableView<br>    )<br>}</pre><pre>// <strong>or</strong><br>func loadView() {<br>    createSegmentedControlView()<br>    createTableView()<br>    createRootView()<br>}<br>// <strong>However, this variant is worse<br>// because the order of function calls here is important<br>// (temporal binding)</strong></pre><p><strong>Principle 7</strong>. Temporal binding is a situation when the order of rows in a function is crucial. Functions should avoid having temporal bindings inside</p><p><em>In practice, it’s impossible to follow this principle in 100% of cases. Even some examples in this article don’t follow it. But it’s nice to reduce the number of temporal bindings as much as possible</em></p><pre>// <strong>Bad</strong><br>function setupSegmentedControlView() {<br>    createSegmentedControlView()<br>    setSegmentedControlConstraints()<br>}<br>// <strong>If setting constraints of the control stays first,</strong><br>// <strong>it will produce a runtime error</strong></pre><pre>// <strong>Good<br></strong>func setupSegmentedControlView() {<br>    self.segmentedControlView = createSegmentedControlView()<br>    setConstraintsOf(segmentedControl: self.segmentedControlView)<br>}<br>// <strong>It&#39;s impossible to call setting constraints</strong><br>// <strong>before the control is created</strong></pre><p><strong>Principle 8</strong>. When it’s not obvious what the function’s call is about, it’s nice to store the call’s result in a variable with an expressive name</p><pre>// <strong>Bad<br></strong>dictionary[regexpMatch.group(0)] = regexpMatch.group(1)</pre><pre>// <strong>Good<br></strong>let id = regexpMatch.group(0)<br>let name = regexpMatch.group(1)<br>dictionary[id] = name</pre><p><strong>Principle 9</strong>. If several conditional operators belong to the same logical condition, they should be compounded into a single function, property, or variable with an expressive name</p><pre>// <strong>Bad<br></strong>if timer.isExpired &amp;&amp; !timer.isRecurrent { ... }</pre><pre>// <strong>Good</strong><br>class Timer {<br>    var shouldBeDeleted: Bool {<br>        return isExpired &amp;&amp; !isRecurrent<br>    }<br>}<br>...<br>if timer.<strong>shouldBeDeleted</strong> { ... }</pre><pre>// <strong>or<br></strong>func shouldTimerBeDeleted(_ timer: Timer) -&gt; Bool {<br>    return timer.isExpired &amp;&amp; !timer.isRecurrent<br>}<br>...<br>if <strong>shouldTimerBeDeleted</strong>(timer) { ... }</pre><p><em>p.s. Every name should be expressive</em></p><p><strong>Principle 10</strong>. Error handling should take a separate layer of abstraction</p><p><em>It shouldn’t be messed up with other logic</em></p><pre>// <strong>This example uses JavaScript (btw, other examples use Swift)<br></strong>//<strong> ... Swift is the best! ;)</strong></pre><pre>// <strong>Bad<br></strong>async function performRequest(...) {<br>    try {<br>        const endpoint = createEndpoint(...)<br>        const body = createRequestBody(...)<br>        const request = createRequest(endpoint, body)<br>        await request.perform()<br>    } catch {<br>        console.log(&quot;Oops. Failed request&quot;)<br>    }<br>}</pre><pre>// <strong>Good</strong><br>async function performRequest(...) {<br>    const endpoint = createEndpoint(...)<br>    const body = createRequestBody(...)<br>    const request = createRequest(endpoint, body)<br>    await request.execute()<br>}<br>async function tryToPerformRequest(...) {<br>    try {<br>        performRequest(...)<br>    } catch {<br>        console.log(&quot;Oops. Failed request&quot;)<br>    }<br>}</pre><p><strong>Principle 11</strong>. Object function should have a higher priority over a static one</p><p><em>The main reason is that a particular function can be polymorphic in the future. But, it doesn’t say that it shouldn’t use a static function at all!</em></p><p><strong>Principle 12</strong>. Function length should be equal to or less than 20 rows. The depths of nesting if/else should be equal to or less than 2</p><h3>Classes, Structures, and Other Custom Types</h3><p><strong>Principle 1</strong>. A class name should stick to the standard naming</p><p><em>E.g., if a class conforms to the BUILDER pattern, its name should contain the ‘Builder’ word — class AccountBuilder</em></p><p><strong>Principle 2</strong>. A protocol name shouldn’t contain the ‘Protocol’ word — ‘AccountSubscriptionProtocol’ It is better to define a protocol<em> ‘</em>AccountSubscription’ but if it has just one class that conforms it, call the class ‘AccountSubscriptionDefault’ which means ‘default’ implementation</p><p><strong>Principle 3</strong>. You should avoid using abstract words like Processor, Data, Info in class/struct names</p><p><em>E.g., what is the difference between Account and AccountInfo? What is the info? There could be Account and AccountLegalDetails</em></p><p><strong>Principle 4</strong>. You should avoid transitive dependencies</p><p><em>Transitive dependencies are difficult to refactor. And they break encapsulation</em></p><pre>class MyCuteBrowser {<br>    let browser: WebBrowser<br>    <br>    func open(url: URL?) { ... }<br>}</pre><pre>let myCuteBrowser = MyCuteBrowser()<br>myCuteBrowser.open(url: URL(&quot;http://google.com&quot;))</pre><pre>// <strong>Bad<br></strong>myCuteBrowser<strong>.browser</strong>.reloadCurrentPage() // <strong>Transitive dependency</strong></pre><pre>// <strong>Good<br></strong>class MyCuteBrowser {<br>    <strong>private</strong> browser: WebBrowser<br>    ...<br>    func reloadCurrentPage() {<br>        browser.reloadCurrentPage()<br>    }<br>}<br>...<br>myCuteBrowser.reloadCurrentPage()</pre><p><strong>Principle 5</strong>. Every class should have the same vertical separation</p><pre>// <strong>There can be used the principle ‘put the code next to its usage’<br></strong>class ViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupTableView()<br>        setupBottomButton()<br>    }<br>    private setupTableView() { ... }<br>    private setupBottomButton() { ... }</pre><pre>    override func updateViewConstraints() {<br>        super.updateViewConstraints()<br>        ...<br>    }<br>}<br>//<strong> internal private private, internal</strong></pre><pre>...</pre><pre>// <strong>Or there can be a single convention about</strong><br>// <strong>where functions and properties should be placed</strong><br>class ViewController: UIViewController {<br>    <strong>// MARK: - Lifecycle</strong><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupTableView()<br>        setupBottomButton()<br>    }<br>    override func updateViewConstraints() {<br>        super.updateViewConstraints()<br>        ...<br>    }</pre><pre>    <strong>// MARK: - Private methods</strong><br>    private setupTableView() { ... }<br>    private setupBottomButton() { ... }<br>}</pre><h3>General</h3><p><strong>Principle 1</strong>. The same word should have just one meaning. And only this word should be used everywhere when talking about the same thing. There should be no other synonyms</p><p><em>E.g., if ‘add’ means appending an element to an array, or a character to a string, don’t use it to have a sum of numbers. Use ‘plus’ for it</em></p><p><em>E.g., if ‘create’ means just creating an object and return it, don’t use it when you want to create something in the database. Use ‘save’ instead. And don’t use synonyms like ‘build’ or ‘make’ Otherwise, rename this word everywhere (DDD, ubiquitous language)</em></p><p><strong>Principle 2</strong>. You should put pieces of code in places where you expect to find them</p><p><em>Suppose you open a class or file to find some function but don’t see it. And then you recall this function is placed in another file. It is nice to think about moving the function to the first file you’ve visited</em></p><p><em>Of course, if it doesn’t contradict architectural principles!</em></p><p><strong>Principle 3</strong>. You shouldn’t use external libraries directly in your code. You should use wrappers on them</p><p><em>Following this principle allows:</em></p><ul><li><em>Having an ability to quickly replace one library with another without changing the rest code (rare case, but still)</em></li><li><em>Picking an interface better for your needs (you can choose another name of a method or even combine several methods to a single one)</em></li><li><em>Writing tests for the wrappers that will tell your teammates how they are used</em></li></ul><p><strong>Principle 4</strong>. Client code shouldn’t be responsible for creating objects, but only for their usages. It should contain a layer consists of factories to create all objects. The FACTORY pattern allows creating objects, entities, satisfying all invariants (hi there, Eric Evans). And the DEPENDENCY INJECTION pattern tells how the objects should be passed around (SOLI<strong>D</strong>, Dependency Inversion Principle)</p><pre>// <strong>Bad<br></strong>class MyCuteBrowser {<br>    private let browser = WebBrowser()<br>    ...<br>}</pre><pre>// <strong>Good<br></strong>class MyCuteBrowser {<br>    private let browser: WebBrowser<br>    <br>    init(browser: WebBrowser) {<br>        self.browser = browser<br>    }<br>}</pre><pre>class MyCuteObjectFactory {<br>    ...<br>    func createMyCuteBrowser() {<br>        return MyCuteBrowser(browser: WebBrowser())<br>    }<br>}</pre><p><strong>Principle 5</strong>. All constants should be defined on the highest level or even in separate config classes/structures rather than be magical values inside the code</p><p><strong>Principle 6</strong>. Having code duplication is bad. Duplicated rows should be moved into a separate function. And repeated switch/case — into some ABSTRACT FACTORY</p><pre>// <strong>Bad</strong><br>func tableView(..., willDisplay cell: UITableViewCell, ...) {<br>    let entity = entities[indexPath.row]<br>    switch entity {<br>        case is Movie: <strong>...<br>        </strong>case is PopularPerson: <strong>...<br>        </strong>default: ...<br>    }<br>}<br>func tableView(..., cellForRowAt indexPath: IndexPath) -&gt; ... {<br>    let entity = entities[indexPath.row]<br>    switch entity {<br>        case is Movie: <strong>...<br>        </strong>case is PopularPerson: <strong>...<br>        </strong>default: ...<br>    }<br>}</pre><pre>// <strong>Good</strong><br>func tableView(..., willDisplay cell: UITableViewCell, ...) {<br>    let entity = entities[indexPath.row]<br>    <strong>getEntityUtilsFactory</strong>(by: entity)<br>        .setMultiSearchTableViewCellImageProperties(<br>            cell: cell,<br>            by: indexPath<br>        )</pre><pre>}<br>func tableView(..., cellForRowAt indexPath: IndexPath) -&gt; ... {<br>    let entity = entities[indexPath.row]<br>    return <strong>getEntityUtilsFactory</strong>(by: entity)<br>        .getMultiSearchTableViewCell(<br>            from: tableView,<br>            by: indexPath<br>        )<br>}<br>func <strong>getEntityUtilsFactory</strong>(<br>    by entity: MultiSearchEntity<br>) -&gt; <strong>EntityUtilsAbstractFactory</strong> {<br>    switch entity {<br>        case is Movie: return movieUtilsFactory<br>        case is PopularPerson: return personUtilsFactory<br>        default: fatalError(&quot;Entity type is unexpected.&quot;)<br>    }<br>}<br>class <strong>EntityUtilsAbstractFactory</strong> {<br>    func setMultiSearchTableViewCellImageProperties(<br>        cell: UITableViewCell,<br>        by indexPath: IndexPath<br>    ) { }<br>    func getMultiSearchTableViewCell(<br>        from tableView: UITableView,<br>        by indexPath: IndexPath<br>    ) -&gt; UITableViewCell {<br>        fatalError(&quot;getTableViewCell(..) must be overridden.&quot;)<br>    }<br>}</pre><p><strong>Principle 7</strong>. You shouldn’t make a decision on how your code will be used</p><p><em>Yet another principle I especially like :) It is related to S</em><strong><em>O</em></strong><em>LID, Open-Closed Principle</em></p><pre>// <strong>Let&#39;s imagine you have a type Person</strong><br>struct Person {<br>   let name: String<br>   let age: Int<br>}</pre><pre>// <strong>And you decided to create a greeting generator for people<br></strong>class PersonGreetingGenerator {<br>    // <strong>And you said: &quot;Oh, it&#39;s always enough to have just a name</strong><br>    // <strong>to create a greeting&quot;<br>    </strong>//<strong> You decided that a person name is enough to use your code<br>    </strong>func createGreetingFor(personName: String) -&gt; String {<br>        return &quot;Hello, \(personName)!&quot;<br>    }<br>}</pre><pre>// <strong>And what&#39;s wrong?</strong></pre><pre>//<strong> Okay. Let&#39;s imagine that we have the following function<br></strong>func greet(<br>    person: Person,<br>    via generator: PersonGreetingGenerator<br>) {<br>    let greeting = generator.createGreetingFor(<br>        personName: person.personName<br>    )<br>    print(greeting)<br>}</pre><pre>// <strong>And we want to generate a special greeting for old people<br></strong>class AgeSpecificPersonGreetingGenerator: PersonGreetingGenerator {<br>    // <strong>Well, now it&#39;s not enough to have just a name<br>    </strong>...</pre><pre>    // <strong>Should we create one more function like this?<br>    </strong>func createGreetingFor(<br>        personName: String,<br>        personAge: Int<br>    ) -&gt; String {<br>        ...<br>    }<br>}</pre><pre>// <strong>But how can we use it with different generators?</strong><br>greet(person: person, via: defaultGenerator)<br>greet(person: oldPerson, via: ageSpecificGenerator)<br>// <strong>Should we create one more function? Or add switch/case there?</strong></pre><pre>// <strong>No</strong></pre><pre>//<strong> We shouldn&#39;t decide what person fields should be used</strong><br>// <strong>We just say: &quot;A person greeting generator works with a person&quot;</strong><br>class PersonGreetingGenerator {<strong><br>    </strong>func createGreetingFor(person: Person) -&gt; String {<br>        return &quot;Hello, \(person.name)!&quot;<br>    }<br>}<br>class AgeSpecificPersonGreetingGenerator: PersonGreetingGenerator {<strong><br>    override </strong>func createGreetingFor(person: Person) -&gt; String {<br>        ...<br>    }<br>}<br>func greet(<br>    person: Person,<br>    via generator: PersonGreetingGenerator<br>) {<br>    let greeting = generator.createGreetingFor(person: <strong>person</strong>)<br>    print(greeting)<br>}</pre><pre>greet(person: person, via: defaultGenerator)<br>greet(person: oldPerson, via: ageSpecificGenerator)</pre><p><strong>Principle 8</strong>. You shouldn’t have pieces of code that are never used</p><p><em>It’s quite a common situation when there are commented rows ‘not to lose changes’ Or class methods included in runtime but never called. Don’t be worry about losing some knowledge. Git remembers everything</em></p><p><strong>Principle 9</strong>. All pieces of code should be consistent — follow the same conventions. However, if the conventions contradict code best practices, they (conventions) should be reconsidered</p><h3>P.S.</h3><p>First of all, I would like to say thanks to Robert Martin and Eric Evans. Almost everything in this article I took from ‘Clean Code’ and ‘Domain-Driven Design’ I’m a big fan of those guys!</p><p>There are principles I didn’t include (TDD, parallel programming, …). I didn’t do it for several reasons:</p><ul><li>I didn’t manage to put some of them into practice</li><li>For now, I’m quite stupid to understand some others</li><li>Some of them I simply might miss while reading</li><li>And others are obvious (follow SOLID, keep modularity, comments are bad, …)</li></ul><p>I highly recommend everyone to read these books. You will find there a right way to design systems and write extensible and readable code. And it can help you to fall in love with the development process, and not consider the development is just a work</p><h3>Another P.S.</h3><p>I think it’s wrong to follow each principle in 100% of cases</p><p>E.g., Apple doesn’t do this when it returns the removed element from an array while using ‘remove(at:)’ — it behaves like a ‘Function’ and ‘Action’ at the same time. And it is quite comfortable to use</p><p>However, when you decide not to follow a particular principle, try to pick a strong defense argument. Because in most cases, these principles work</p><h3>And The Last P.S.</h3><p>Keep your code straightforward. Don’t try to use elaborate solutions with generic types, tons of abstractions, etc. People call it ‘overengineering’</p><p>Sometimes I check myself by showing my code to people who are quite far from development. And if I’m writing on Swift, a Java developer should mostly understand it, at least its Domain part</p><p>In the very beginning, I saw complicated code written by ‘senior developers’ I worked with. It was QUITE challenging to understand it, and when I came at them and asked: “Could you, please, clarify what is going here?” They said: “What exactly you didn’t understand?”</p><p>Funny…</p><p>I felt so stupid because I understood almost nothing and didn’t manage to identify particular things</p><p>Well, looking at their code today and keeping in mind the principles and how it could be, I wouldn’t say: “Could you, please, clarify..” anymore. I would say: “Could you, please, refactor this piece of shit? My time is valuable enough not to spend it digging in over 100-row functions, to check that you correctly build a request object and send it to the server”</p><h3>References</h3><ul><li>Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin</li><li>Domain-Driven Design: Tackling Complexity in the Heart of Software, by Eric Evans</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c8f665b6cdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Concurrency]]></title>
            <link>https://maxim-kryloff.medium.com/swift-concurrency-810fdbe0b248?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/810fdbe0b248</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 06:19:03 GMT</pubDate>
            <atom:updated>2021-05-29T16:37:59.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p>When talking about concurrency in Swift, it is <strong>queues </strong>that are usually meant</p><p>A queue is an array of tasks, each of which starts execution in the order they were added. The main execution thread is also a queue that is called <strong>main</strong></p><p>There are two types of queues: <strong>serial</strong> and <strong>concurrent</strong></p><p>In a <strong>serial</strong> queue, tasks run one by one. The next task won’t be kicked off until the previous one is finished</p><p>In a <strong>concurrent </strong>queue, tasks are also run one by one. However, each task is executed on a separate thread, and the queue doesn’t wait for the previous task to run the next one. The next task immediately starts if it’s enough resources for having one more thread</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kLEmTBWRe-IWs3lRulogA.png" /></figure><p>A task can be added to <strong>any queue</strong> in two ways: <em>sync </em>and <em>async</em></p><p>When adding a task via the method <em>sync</em>, <strong>the current thread gets blocked</strong> until the task is finished — no matter whether the queue is serial or concurrent</p><p>When using the method <em>async</em>, <strong>the current thread</strong> conversely <strong>proceeds execution immediately</strong> after adding the task</p><p>The current thread itself can be main, or one more serial or concurrent queue</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw7NVWb3NxWo6SSOBl7RGg.png" /></figure><h3>Concurrency Issues</h3><ul><li><strong>Race condition</strong> — a result depends on the order of concurrent task execution. The order may be different on each running</li><li><strong>Priority inversion</strong> — priority of a particular task is unexpectedly increased or decreased</li><li><strong>Deadlock</strong> — threads are blocked because their tasks are waiting for resources that are interlocked by them</li></ul><p>A race condition occurs when concurrent tasks change shared resources. And depending on the order of those changes, the resources have different values</p><p>Priority inversion appears when concurrent tasks are waiting for shared resources that are locked by other tasks. As a result, even if their priorities are higher than others, they have to wait for low-priority tasks to get access to the locked resources</p><p>Deadlock is the most dangerous concurrency issue. It happens if there is <strong>nested concurrent access</strong> to shared resources. Let’s say there is a nested concurrent task. It is waiting for resources, which are locked by the enclosing task. And the enclosing task itself is waiting for the nested task is completed. So, both threads are entirely blocked by each other</p><p>Adding a task to a queue from the main thread through the method <em>sync</em> can cause deadlock. <strong>Don’t add tasks from the main thread via <em>sync </em>ever!</strong></p><h3>Grand Central Dispatch (GCD)</h3><p><em>DispatchQueue</em> is the main class of GCD</p><pre>let queue = <strong>DispatchQueue</strong>(label: &quot;queue&quot;)<br>queue.<strong>async</strong> { print(&quot;queue&quot;) }<br>print(&quot;main&quot;)</pre><pre>// <strong>main<br></strong>// <strong>queue</strong></pre><p><em>DispatchQueue</em> has a reference to the<strong> main</strong> queue and <strong>five</strong> <strong>global</strong> <strong>concurrent</strong> queues, which differ in their <strong>Quality of Service </strong>(priority) or <strong>QoS</strong>:</p><ul><li><em>.userInteractive</em> — is the highest QoS. It is used for tasks, which <strong>are triggered by </strong>a<strong> user</strong> and have to be completed first of all. The tasks shouldn’t take much time. E.g., a user is running a finger on the screen. There is a logic to handle the user action that takes some time for responding. That logic can be added as an async task to the queue with the highest priority to avoid producing UI lags. The main thread itself will proceed to listen to other user actions</li><li><em>.userInitiated</em> — is less than the previous one, but still relatively high. The tasks<strong> should respond to user actions</strong> as soon as possible, but the user may wait for a while (several seconds). E.g., the user has pressed a button and is waiting for the result</li><li><em>.utility</em> — is a middle QoS. The tasks <strong>aren’t triggered</strong> by a user, and they can take more than several seconds. E.g., a user goes on a screen, and it should download and show some image there. Until the image is shown, the user sees an activity indicator</li><li><em>.background</em> — is the lowest QoS. The tasks <strong>aren’t related to UI</strong> and <strong>visualization </strong>at all. They can take even hours. E.g., synchronization with iCloud</li><li><em>.default</em> — trying to take QoS from other sources. Otherwise, it sets the priority between <em>.userInitiated</em> and <em>.utility</em></li></ul><p>It is crucial to keep in mind that the global queues are <strong>system </strong>ones. And they can contain not only custom tasks</p><pre>DispatchQueue.<strong>global</strong>(qos: .<strong>userInteractive</strong>).async { ... }<br>DispatchQueue.<strong>global</strong>(qos: .<strong>userInitiated</strong>).async { ... }<br>DispatchQueue.<strong>global</strong>(qos: .<strong>utility</strong>).async { ... }<br>DispatchQueue.<strong>global</strong>(qos: .<strong>background</strong>).async { ... }<br>DispatchQueue.<strong>global</strong>().async { ... }</pre><p>The<em> main</em> queue is the main thread. Any UI update can be made <strong>only</strong> there. The <em>main </em>queue<em> </em>is the unique <strong>serial </strong>global queue. It shouldn’t have tasks that take a lot of resources or much time</p><pre>DispatchQueue.main.<strong>async</strong> { ... }<br>// <strong>btw, again don&#39;t do DispatchQueue.main.sync { ... } ever!</strong></pre><pre>// <strong>Experiment 1: main queue === main thread</strong></pre><pre>func currentQueueName() -&gt; String? {<br>    let name = __dispatch_queue_get_label(nil)<br>    return String(cString: name, encoding: .utf8)<br>}</pre><pre>print(<strong>currentQueueName()</strong>!)<br>DispatchQueue.<strong>main</strong>.async {<br>    print(<strong>currentQueueName()</strong>!)<br>}</pre><pre>//<strong> com.apple.main-thread<br></strong>//<strong> com.apple.main-thread</strong></pre><pre>// <strong>Experiment 2: global dispatch queue - sync vs async</strong></pre><pre>func task(_ symbol: String) {<br>    let priority = qos_class_self().rawValue<br>    for i in 0...3 {<br>        print(&quot;\(symbol), i: \(i), priority: \(priority)&quot;)<br>    }<br>}</pre><pre>DispatchQueue.global().<strong>sync</strong> { task(&quot;😁&quot;) }<br>task(&quot;😈&quot;)<br>/*<br>😁<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 33<br></strong>😁<strong>, i: 3, priority: 33<br></strong>😈<strong>, i: 0, priority: 33<br></strong>😈<strong>, i: 1, priority: 33<br></strong>😈<strong>, i: 2, priority: 33<br></strong>😈<strong>, i: 3, priority: 33<br></strong>*/</pre><pre>// <strong>vs</strong></pre><pre>DispatchQueue.global().<strong>async</strong> { task(&quot;😁&quot;) }<br>task(&quot;😈&quot;)<br>/*<br>😈<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 0, priority: 25<br></strong>😈<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 1, priority: 25<br></strong>😈<strong>, i: 2, priority: 33<br></strong>😈<strong>, i: 3, priority: 33<br></strong>😁<strong>, i: 2, priority: 25<br></strong>😁<strong>, i: 3, priority: 25<br></strong>*/</pre><pre>// <strong>Experiment 3: global dispatch queue - priorities</strong></pre><pre>DispatchQueue.<strong>main</strong>.async { task(&quot;😁&quot;) }<br>DispatchQueue.global(qos: .<strong>userInteractive</strong>).async { task(&quot;😈&quot;) }<br>DispatchQueue.global(qos: .<strong>userInitiated</strong>).async { task(&quot;👻&quot;) }<br>DispatchQueue.global(qos: .<strong>utility</strong>).async { task(&quot;🤖&quot;) }<br>DispatchQueue.global(qos: .<strong>background</strong>).async { task(&quot;😾&quot;) }<br>/*<br>👻<strong>, i: 0, priority: 25<br></strong>😈<strong>, i: 0, priority: 33<br></strong>🤖<strong>, i: 0, priority: 17<br></strong>😾<strong>, i: 0, priority: 9<br></strong>👻<strong>, i: 1, priority: 25<br></strong>😈<strong>, i: 1, priority: 33<br></strong>😈<strong>, i: 2, priority: 33<br></strong>😈<strong>, i: 3, priority: 33<br></strong>👻<strong>, i: 2, priority: 25<br></strong>👻<strong>, i: 3, priority: 25<br></strong>🤖<strong>, i: 1, priority: 17<br></strong>🤖<strong>, i: 2, priority: 17<br></strong>🤖<strong>, i: 3, priority: 17<br></strong>😁<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 33<br></strong>😁<strong>, i: 3, priority: 33<br></strong>😾<strong>, i: 1, priority: 9<br></strong>😾<strong>, i: 2, priority: 9<br></strong>😾<strong>, i: 3, priority: 9<br></strong>*/</pre><p>Along with the global queues, <em>DispatchQueue</em> also enables to create private ones. When creating a private queue, it requires to provide a <em>label</em> that <strong>must</strong> be unique. Apple suggests naming the <em>label</em> in accordance with inverse domain notation, e.g., “com.myApp.myQueue”</p><p>By default, any private dispatch queue is <strong>serial</strong></p><pre>// <strong>Experiment 4: private dispatch queue by default is serial</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;)<br>myQueue.async { task(&quot;😁&quot;) }<br>myQueue.async { task(&quot;😈&quot;) }<br>/*<br>😁<strong>, i: 0, priority: 25<br></strong>😁<strong>, i: 1, priority: 25<br></strong>😁<strong>, i: 2, priority: 25<br></strong>😁<strong>, i: 3, priority: 25<br></strong>😈<strong>, i: 0, priority: 25<br></strong>😈<strong>, i: 1, priority: 25<br></strong>😈<strong>, i: 2, priority: 25<br></strong>😈<strong>, i: 3, priority: 25<br></strong>*/</pre><pre>// <strong>Experiment 4: serial dispatch queue - async</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;) // <strong>serial</strong><br>myQueue.<strong>async</strong> { task(&quot;😁&quot;) }<br>task(&quot;😈&quot;)<br>/*<br>😈<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 0, priority: 25<br></strong>😁<strong>, i: 1, priority: 25<br></strong>😈<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 25<br></strong>😁<strong>, i: 3, priority: 25<br></strong>😈<strong>, i: 2, priority: 33<br></strong>😈<strong>, i: 3, priority: 33<br></strong>*/</pre><p>The second parameter of a private dispatch queue is <em>qos</em></p><pre>// <strong>Experiment 5: private dispatch queue - priorities</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .<strong>userInteractive</strong>)<br>let yourQueue = DispatchQueue(label: &quot;com.myApp.yourQueue&quot;, qos: .<strong>background</strong>)</pre><pre>myQueue.async { task(&quot;😁&quot;) }<br>yourQueue.async { task(&quot;😈&quot;) }<br>/*<br>😈<strong>, i: 0, priority: 9<br></strong>😁<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 33<br></strong>😁<strong>, i: 3, priority: 33<br></strong>😈<strong>, i: 1, priority: 9<br></strong>😈<strong>, i: 2, priority: 9<br></strong>😈<strong>, i: 3, priority: 9<br></strong>*/</pre><p>The experiment above shows that there are at least two ways of having concurrent behavior: either it is a single concurrent queue, or it is several queues (they can be serial), but tasks should be added there via the method <em>async</em></p><p>For having a private <strong>concurrent</strong> queue, the third parameter <em>attributes </em>should obtain <em>.concurrent</em> flag</p><pre>// <strong>Experiment 6: concurrent private dispatch queue</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, attributes: [.<strong>concurrent</strong>])</pre><pre>myQueue.async { task(&quot;😁&quot;) }<br>myQueue.async { task(&quot;😈&quot;) }<br>/*<br>😈<strong>, i: 0, priority: 25<br></strong>😁<strong>, i: 0, priority: 25<br></strong>😁<strong>, i: 1, priority: 25<br></strong>😈<strong>, i: 1, priority: 25<br></strong>😁<strong>, i: 2, priority: 25<br></strong>😈<strong>, i: 2, priority: 25<br></strong>😁<strong>, i: 3, priority: 25<br></strong>😈<strong>, i: 3, priority: 25<br></strong>*/</pre><p>By default, a task that is added to a queue starts automatically when the conditions are satisfied. For having manual running, there should be specified the <em>.initiallyInteractive</em> flag</p><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, attributes: [.concurrent, .<strong>initiallyInactive</strong>])</pre><pre>myQueue.async { task(&quot;😁&quot;) }<br>myQueue.async { task(&quot;😈&quot;) }</pre><pre>myQueue<strong>.activate</strong>()</pre><p>The next class of GCD is <em>DispatchWorkItem</em>. It is a kind of a wrapper on dispatch queue tasks</p><p><em>DispatchWorkItem </em>can be used for changing the priority of a particular task over the whole dispatch queue. It can be reached via providing the<em> .enforceQoS </em>flag</p><pre>// <strong>Experiment 7: DispatchWorkItem and .enforceQoS</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .<strong>background</strong>,  attributes: [.<strong>concurrent</strong>])</pre><pre>let workItem = <strong>DispatchWorkItem</strong>(qos: .<strong>userInteractive</strong>, flags: [.<strong>enforceQoS</strong>]) {<br>    task(&quot;😁&quot;)<br>}</pre><pre>myQueue.async { task(&quot;😈&quot;) }<br>myQueue.async(execute: workItem)<br>/*<br>😈<strong>, i: 0, priority: 9<br></strong>😁<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 33<br></strong>😁<strong>, i: 3, priority: 33<br></strong>😈<strong>, i: 1, priority: 9<br></strong>😈<strong>, i: 2, priority: 9<br></strong>😈<strong>, i: 3, priority: 9<br></strong>*/</pre><p>The method <em>cancel()</em> of <em>DispatchWorkItem</em> enables to mark a task in a queue <em>isCanceled</em>. The method doesn’t allow to cancel an async task already being executed (see Operation and OperationQueue). However, it can prevent a task from being running. E.g., having <em>DispatchWorkItem </em>and <em>cancel()</em> helps to implement debounce logic</p><pre>class <strong>Debounce</strong>ActionService {<br>    private let debounceQueue = DispatchQueue(<br>        label: UUID().uuidString,<br>        attributes: [.concurrent]<br>    )<br>    private var debounceWorkItem: DispatchWorkItem?</pre><pre>    public func asyncAfter(<br>        delay: DispatchTimeInterval,<br>        _ callback: @escaping () -&gt; Void = {}<br>    ) {<br>        debounceWorkItem?.cancel()<br>        debounceWorkItem = DispatchWorkItem(block: callback)<br>        debounceQueue.asyncAfter(<br>            deadline: .now() + delay,<br>            execute: debounceWorkItem!<br>        )<br>    }<br>}</pre><p>For having a completion logic that should be triggered after a work item is finished, there should be used the method <em>notify</em></p><pre>// <strong>Experiment 8: DispatchWorkItem and notify</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .background, attributes: [.concurrent]<br>let workItem = DispatchWorkItem(qos: .userInteractive, flags: [.enforceQoS]) { task(&quot;😁&quot;) }</pre><pre>myQueue.async(execute: workItem)<br>workItem.<strong>notify</strong>(queue: DispatchQueue.main) {<br>    print(&quot;work item has been finished&quot;)<br>}<br>task(&quot;😈&quot;)<br>/*<br>😁<strong>, i: 0, priority: 33<br></strong>😈<strong>, i: 0, priority: 33<br></strong>😁<strong>, i: 1, priority: 33<br></strong>😈<strong>, i: 1, priority: 33<br></strong>😁<strong>, i: 2, priority: 33<br></strong>😈<strong>, i: 2, priority: 33<br></strong>😁<strong>, i: 3, priority: 33<br></strong>😈<strong>, i: 3, priority: 33<br>work item has been finished<br></strong>*/</pre><p><strong>Note: </strong><em>notify</em> adds a task to a specific queue via <em>async</em></p><p>The class <em>DispatchGroup </em>is helpful when there are several async tasks, and all of them must be completed before having particular logic</p><pre>// <strong>Experiment 9: DispatchGroup and notify</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .background,  attributes: [.concurrent])</pre><pre>let <strong>dispatchGroup</strong> = DispatchGroup()<br>myQueue.async(group: <strong>dispatchGroup</strong>) { task(&quot;😁&quot;) }<br>myQueue.async(group: <strong>dispatchGroup</strong>) { task(&quot;😈&quot;) }<br>dispatchGroup.<strong>notify</strong>(queue: DispatchQueue.main) { print(&quot;done&quot;) }<br>/*<br>😁<strong>, i: 0, priority: 9<br></strong>😈<strong>, i: 0, priority: 9<br></strong>😈<strong>, i: 1, priority: 9<br></strong>😁<strong>, i: 1, priority: 9<br></strong>😈<strong>, i: 2, priority: 9<br></strong>😈<strong>, i: 3, priority: 9<br></strong>😁<strong>, i: 2, priority: 9<br></strong>😁<strong>, i: 3, priority: 9<br>done<br></strong>*/</pre><p>If a task has an async operation inside that has to be finished before doing something, there can be used <em>DispatchGroup</em> the methods <em>enter()</em> and <em>leave()</em></p><pre>// <strong>Experiment 9: DispatchGroup and notify - enter and leave</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .background,  attributes: [.concurrent])</pre><pre>let dispatchGroup = DispatchGroup()<br>myQueue.async(group: dispatchGroup) {<br>    dispatchGroup.<strong>enter</strong>()<br>    DispatchQueue.global().<strong>asyncAfter(deadline: .now() + 1.0)</strong> {<br>        task(&quot;😁&quot;)<br>        dispatchGroup.<strong>leave</strong>()<br>    }<br>}<br>myQueue.async(group: dispatchGroup) {<br>    dispatchGroup.<strong>enter</strong>()<br>    DispatchQueue.global().<strong>asyncAfter(deadline: .now() + 1.0)</strong> {<br>        task(&quot;😈&quot;)<br>        dispatchGroup.<strong>leave</strong>()<br>    }<br>}<br>dispatchGroup.notify(queue: DispatchQueue.main) {<br>    print(&quot;done&quot;)<br>}<br>/*<br>😈<strong>, i: 0, priority: 9<br></strong>😁<strong>, i: 0, priority: 9<br></strong>😈<strong>, i: 1, priority: 9<br></strong>😁<strong>, i: 1, priority: 9<br></strong>😈<strong>, i: 2, priority: 9<br></strong>😁<strong>, i: 2, priority: 9<br></strong>😈<strong>, i: 3, priority: 9<br></strong>😁<strong>, i: 3, priority: 9<br>done<br></strong>*/</pre><p>A <strong>barrier task</strong> is a task that is added to a <strong>concurrent</strong> queue (it doesn’t make sense for a <strong>serial</strong> one) to wait for all tasks before the barrier, then execute the barrier task itself (it is guaranteed that there can be no other running task in the queue during the barrier task execution), and after all, do away with other tasks in that queue</p><p>To enable the barrier logic, GCD sets a particular task in a dispatch queue as a barrier one via the flag <em>.barrier</em></p><pre>// <strong>Experiment 9: .barrier</strong></pre><pre>let myQueue = DispatchQueue(label: &quot;com.myApp.myQueue&quot;, qos: .background,  attributes: [.<strong>concurrent</strong>])</pre><pre>myQueue.async { task(&quot;😁&quot;) }<br>myQueue.async { task(&quot;😈&quot;) }<br>myQueue.async(flags: <strong>.barrier</strong>) { task(&quot;✋&quot;)}<br>myQueue.async { task(&quot;👻&quot;) }<br>/*<br>😈, i: 0, priority: 9<br>😁, i: 0, priority: 9<br>😁, i: 1, priority: 9<br>😁, i: 2, priority: 9<br>😈, i: 1, priority: 9<br>😁, i: 3, priority: 9<br>😈, i: 2, priority: 9<br>😈, i: 3, priority: 9<br><strong>✋, i: 0, priority: 9<br>✋, i: 1, priority: 9<br>✋, i: 2, priority: 9<br>✋, i: 3, priority: 9</strong><br>👻, i: 0, priority: 9<br>👻, i: 1, priority: 9<br>👻, i: 2, priority: 9<br>👻, i: 3, priority: 9<strong><br></strong>*/</pre><h3>Thread-Safe Variable Pattern</h3><pre>// <strong>Problem</strong></pre><pre>var result = 1</pre><pre>let queue = DispatchQueue(label: &quot;com.queue&quot;, attributes: [.concurrent])</pre><pre>queue.async {<br>    for _ in 0..&lt;3 {<br>        // <strong>let&#39;s say that 2 is a quite expensive operation</strong>        <br>        result = result *<strong> 2</strong><br>    }<br>}<br>queue.async {<br>    for _ in 0..&lt;3 {<br>        result = result *<strong> 2</strong><br>    }<br>}</pre><pre>sleep(1)<br>print(result)</pre><pre><strong>// We want to make concurrent computing of result,<br>// because 2 is expensive for doing it in a serial manner</strong><br>// <strong>But</strong> <strong>here is a race condition. The result can be 8, 16, 32...<br></strong>// <strong>However the correct result is 64</strong></pre><pre>// <strong>Solution</strong></pre><pre>class <strong>ThreadSafeResult</strong> {<br>    // <strong>serial queue<br>    </strong>private let queue = DispatchQueue(label: UUID().uuidString)<br>    private var resultValue = 0</pre><pre>    public init(_ value: Int) {<br>        set(value: value)<br>    }</pre><pre>    public func <strong>set</strong>(value: Int) {<br>        queue.<strong>async </strong>{<br>            self.resultValue = value<br>        }<br>    }</pre><pre>    public func <strong>add</strong>(value: Int) {<br>        queue<strong>.async</strong> { <br>            self.resultValue = self.resultValue * value <br>        }<br>    }</pre><pre>    public var <strong>value</strong>: Int {<br>        var resultValue = 0<br>        queue.<strong>sync</strong> { resultValue = self.resultValue }<br>        return resultValue<br>    }<br>}</pre><pre>var result = ThreadSafeResult(1)</pre><pre>let queue = DispatchQueue(label: &quot;com.queue&quot;, attributes: [.concurrent])</pre><pre>queue.async {<br>    for _ in 0..&lt;3 {<br>        result.add(value: <strong>2</strong>) // <strong>still concurrent computing of 2</strong><br>    }<br>}</pre><pre>queue.async {<br>    for _ in 0..&lt;3 {<br>        result.add(value: <strong>2</strong>) // <strong>still concurrent computing of 2</strong><br>    }<br>}</pre><pre>sleep(1)<br>print(result.value)</pre><pre>// <strong>64, no race condition</strong></pre><p>Any thread-safe variable should satisfy the following requirements:</p><ul><li>Each <strong>write</strong> operation is <strong>async</strong>. There cannot be two or more write operations at the same time</li><li>Each <strong>read</strong> operation is <strong>sync</strong>. Any time when the operation is being executed, all write operations started before must be completed</li></ul><p>The pattern puts a particular write operation into a single <strong>serial</strong> queue via the method <em>async</em>. Thus, because the queue is serial, there can be no concurrent changes that might happen in different threads (the first requirement is met). And because any read operation uses the method <em>sync </em>and takes place in the same serial queue, it is guaranteed that all operations before reading will be completed (the second requirement is met)</p><p>In the pattern, it also can use a <strong>concurrent</strong> queue instead of a serial one. And then all async write operations must be added as <strong>barriers</strong></p><h3>Operation and OperationQueue</h3><p><em>Operation</em> — is an OOP wrapper on a task. It has a state machine that enables to control of an operation before and during its execution. Also, it allows making a particular operation dependant on another operation</p><p><em>OperationQueue</em> — is an OOP wrapper on a <em>DispatchQueue</em>. Any task there is an <em>Operation</em>. Tasks can be added via the method <em>addOperation</em> as a simple closure or an instance of <em>Operation</em></p><p><em>addOperation</em> is <strong>async </strong>function</p><pre>let operationQueue = OperationQueue()<br>operationQueue.<strong>addOperation</strong> { print(&quot;hello world&quot;) }</pre><p>By default, an operation is kicked off automatically after getting to a queue. For manual running, an operation has the method <em>start()</em></p><p><em>start() </em>itself<em> </em>is a <strong>sync </strong>function. The current thread won’t proceed with execution until the operation is finished</p><pre>let someOperation = Operation()<br>someOperation.<strong>start</strong>()</pre><p>Each operation can be executed just once. The second attempt to run a completed operation (via the method <em>start() </em>or <em>addOperation</em>) will produce a runtime error</p><pre>let operationQueue = OperationQueue()<br>let anotherOperationQueue = OperationQueue(<br>let operation = Operation()<br>operationQueue.addOperation(operation)<br>anotherOperationQueue.addOperation(operation) // <strong>runtime error</strong></pre><pre>// <strong>or</strong></pre><pre>let operation = Operation()<br>operation.start()<br>operation.start()                             // <strong>runtime error</strong></pre><p>A particular operation can also be created via <em>BlockOperation</em></p><blockquote>The <strong>BlockOperation</strong> class is a concrete <strong>subclass</strong> of <strong>Operation</strong> that manages the <strong>concurrent</strong> execution of one or more blocks. You can use this object to execute several blocks at once without having to create separate operation objects for each. When executing more than one block, the operation itself is considered finished only when all blocks have finished executing.</blockquote><pre>let blockOperation = <strong>BlockOperation</strong> {<br>    sleep(1)<br>    print(&quot;hello&quot;)<br>}</pre><pre>blockOperation.addExecutionBlock {<br>    print(&quot;world&quot;)<br>}</pre><pre>let operationQueue = OperationQueue()<br>operationQueue.addOperation(blockOperation)</pre><pre>// <strong>world</strong><br>// <strong>hello</strong></pre><p>For having a custom operation, there should be a class that inherits from <em>Operation </em>and overrides the method <em>main()</em></p><pre>class CustomOperation<strong>: Operation</strong> {<br>    public var operationName = &quot;&quot;<br>   <br>    <strong>override </strong>func<strong> main()</strong> {<br>        print(&quot;hello from \(operationName)&quot;)<br>    }<br>}</pre><pre>let operation = CustomOperation()<br>operation.operationName = &quot;custom operation&quot;<br>operation.start()</pre><pre>// <strong>hello from custom operation</strong></pre><p>Any operation can be provisioned with a <em>completionBlock — </em>a<em> </em>closure that will <strong>always </strong>be executed after the operation gets<strong> finished</strong></p><pre>operation.completionBlock = {<br>    print(&quot;hello from completion block&quot;)<br>}</pre><p>Also, it’s possible to set <em>qualityOfService</em> for each particular operation via the corresponding property. Otherwise, the operation takes QoS from its queue</p><p>The state machine represents an operation life cycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqtEhE9bHKVb1IYJoWKutw.png" /></figure><p>When getting to a queue, an operation has the state <em>pending</em>. Then after a while, it gets <em>ready</em>. Once the queue starts operation execution, the state is <em>executing</em>. After the operation is completed, it has the state <em>finished</em>. Any time the operation can be cancelled via the method <em>cancel().</em> Then the state is <em>cancelled</em></p><p>The corresponding properties <em>isReady</em>, <em>isExecuting</em>, <em>isFinished</em>, and <em>isCancelled </em>allow checking the operation state</p><h3>Async Operation Pattern</h3><p>If a custom operation doesn’t contain any async logic inside, it is enough to override the method <em>main()</em> and rely on a queue and the operation state machine</p><p>The problem of having an async logic is that when the logic starts, the current thread immediately proceeds execution. As a result, an operation that has an async logic will be finished before the logic gets completed</p><p>The pattern enables to control of the states manually. So, it allows us to set the operation state to <em>finished </em>only when the async logic will be completed</p><pre>class AsyncOperation: Operation {<br>  <br>    public <strong>enum State</strong>: String {<br>        case isReady, isExecuting, isFinished<br>    }</pre><pre>    public var state: State = .isReady {<br>        willSet {<br>            willChangeValue(forKey: newValue.rawValue)<br>            willChangeValue(forKey: state.rawValue)<br>        }<br>        didSet {<br>            didChangeValue(forKey: oldValue.rawValue)<br>            didChangeValue(forKey: state.rawValue)<br>        }<br>    }</pre><pre>    override var isReady: Bool {<br>        // <strong>super.isReady is used to preserve dependencies logic<br>        </strong>return super.isReady &amp;&amp; state == .isReady<br>    }</pre><pre>    override var isExecuting: Bool {<br>        return state == .isExecuting<br>    }</pre><pre>    override var isFinished: Bool {<br>        return state == .isFinished<br>    }</pre><pre>    override var isAsynchronous: Bool {<br>        return true<br>    }</pre><pre>    override func start() {<br>        if isCancelled {<br>            state = .isFinished<br>            return<br>        }<br>        main()<br>        state = .isExecuting<br>    }</pre><pre>    override func cancel() {<br>        super.cancel() // <strong>marks the operation isCancelled</strong><br>        state = .isFinished<br>    }<br>}</pre><p>Through the methods <em>willChangeValue </em>and <em>didChangeValue</em>, which are based on KVO, an operation can recalculate the value of the state properties. But because the properties <em>isReady</em>, <em>isExecuting</em>, <em>isFinished </em>are read-only, it introduces the property <em>state</em> used inside them, that stores the state of the operation and can be manually set to any state during the recalculation</p><pre>// <strong>Custom async operation example</strong></pre><pre>class DownloadImageOperation: AsyncOperation {<br>    <br>    public var url: URL<br>    public var image: UIImage?</pre><pre>    init(url: URL) {<br>        self.url = url<br>        super.init()<br>    }</pre><pre>    override func main() {<br>        if isCancelled {<br>            return<br>        }<br>        downloadImage()<br>    }</pre><pre>    private func downloadImage() {<br>        let task = createDownloadImageTask()<br>        task.resume()<br>    }</pre><pre>    private func createDownloadImageTask() -&gt; URLSessionDataTask {<br>        return URLSession.shared.dataTask(with: url) { (data, _, _) in<br>            if self.isCancelled {<br>                return<br>            }<br>            guard let data = data else {<br>                self.state = .isFinished<br>                return<br>            }<br>            self.image = UIImage(data: data)<br>            self.state = .isFinished<br>        }<br>    }<br>}</pre><pre>// <strong>...</strong></pre><pre>let operation = DownloadImageOperation(url: url)<br>operation.qualityOfService = .utility<br>operation.completionBlock = {<br>    if operation.isCancelled {<br>        return<br>    }<br>    callback(operation.image, url)<br>}</pre><p><em>OperationQueue</em> has a static reference to the main thread — <em>main</em>, and also it has static property <em>current</em>, referring to the current thread</p><pre>let queue = OperationQueue()<br>queue.addOperation {<br>    print(&quot;current thread is \(OperationQueue.<strong>current</strong>!.name!)&quot;)<br>    print(&quot;main thread is \(OperationQueue.<strong>main</strong>.name!)&quot;)<br>}</pre><pre>// <strong>current thread is NSOperationQueue 0x7fb4ee6080a0<br></strong>//<strong> main thread is NSOperationQueue Main Queue</strong></pre><p>By default, any <em>OperationQueue</em> is <strong>concurrent</strong>. It takes as many threads for operations as available. For making a queue serial, the property <em>maxConcurrentOperationCount</em> should be set to <em>1</em></p><pre>queue.maxConcurrentOperationCount = 1 // <strong>makes the queue serial</strong></pre><p>It is possible to cancel all operations inside a queue via the method <em>cancelAllOperations()</em>. The method invokes <em>cancel()</em> of each particular operation</p><pre>queue.cancelAllOperations()</pre><p><em>OperationQueue </em>provides the method <em>waitUntilAllOperationsAreFinished()</em> to wait for all operations inside before having some logic. <strong>However</strong>, comparing to <em>DispatchGroup </em>and <em>notify</em>, the method <em>waitUntilAllOperationsAreFinished() </em><strong>blocks</strong> the <strong>current thread</strong></p><pre>queue.waitUntilAllOperationsAreFinished() // <strong>blocks current thread</strong></pre><p>The queue property <em>qualityOfService</em> sets QoS for all operations inside the queue. By default the property value equals to <em>.background</em></p><pre>queue.qualityOfService = .utility // .<strong>background by default</strong></pre><p><em>OperationQueue</em> also allows adding operations without automatic running. For making it available, the property <em>isSuspended </em>should be set to <em>true</em>. It doesn’t affect operations that were added before setting the property. But new operations won’t be started until the property is set back to <em>false</em></p><pre>queue.isSuspended = true</pre><p>Each <em>Operation</em> can have dependencies. A particular operation won’t be kicked off while it has dependencies, which are not completed</p><p>To add or remove a dependency there should be invoked the corresponding methods <em>addDependency </em>and <em>removeDependency</em></p><pre>let operationA = BlockOperation { print(&quot;A&quot;) }<br>let operationB = BlockOperation { print(&quot;B&quot;) }<br>let operationC = BlockOperation { print(&quot;C&quot;) }</pre><pre>operationA.<strong>addDependency</strong>(operationB)<br>operationA.<strong>addDependency</strong>(operationC)</pre><pre>let queue = OperationQueue()<br>queue.addOperation(operationA)<br>queue.addOperation(operationB)<br>queue.addOperation(operationC)</pre><pre>//<strong> B<br></strong>//<strong> C<br></strong>//<strong> A</strong></pre><p>The property <em>dependencies</em> stores all operation dependencies. It can be useful for transferring data between operations</p><pre>// <strong>somewhere inside in custom operation</strong></pre><pre>override func main() {<br>    for operation in <strong>dependencies</strong>.filter({ $0 is SomeOperation }) {<br>        print((operation as! SomeOperation).data)<br>    }<br>}</pre><p>But having a complicated graph of dependencies <strong>can cause deadlock</strong></p><p><em>OperationQueue</em> also supports the barrier mechanism. The method <em>addBarrierBlock</em> enables to add some barrier piece of code into a particular queue</p><pre>queue.addBarrierBlock { print(&quot;barrier&quot;) }</pre><h3>GCD vs OperationQueue</h3><p><em>OperationQueue</em> is very useful for having<strong> async operations</strong> and <strong>dependencies</strong>. It has an easy way to cancel operations. However, waiting for operations blocks threads. And <em>OperationQueue </em>itself <strong>is slower </strong>than GCD (milliseconds vs. nanoseconds)</p><p>GCD is appropriate for having<strong> simple tasks</strong> that should be computed in other threads. Even if there is a <strong>simple</strong> <strong>async task</strong>, GCD can use <em>DispatchGroup </em>methods <em>enter()</em> and <em>leave() </em>to<em> </em>wait for the async logic before doing something. And <em>DispatchGroup</em> itself allows waiting for tasks without any thread blocking. But for complicated tasks and dependencies, it may be still better to use <em>OperationQueue</em></p><h3>Resources</h3><ul><li><a href="https://habr.com/en/post/320152/">https://habr.com/en/post/320152/</a></li><li><a href="https://habr.com/en/post/335756/">https://habr.com/en/post/335756/</a></li><li><a href="https://developer.apple.com/documentation/foundation/blockoperation">https://developer.apple.com/documentation/foundation/blockoperation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=810fdbe0b248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Generics]]></title>
            <link>https://maxim-kryloff.medium.com/swift-generics-4faa1cb0b930?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4faa1cb0b930</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 19:37:12 GMT</pubDate>
            <atom:updated>2021-05-29T16:37:38.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p>Generics can be used when defining a function</p><pre>// <strong>Generic function</strong></pre><pre>func swapTwoValues<strong>&lt;T&gt;</strong>(_ first: inout <strong>T</strong>, _ second: inout <strong>T</strong>) {<br>    let temp = first<br>    first = second<br>    second = temp<br>}</pre><pre>var firstInt = 3<br>var secondInt = 5<br>swapTwoValues(&amp;firstInt, &amp;secondInt)</pre><pre>var firstString = &quot;hello&quot;<br>var secondString = &quot;world&quot;<br>swapTwoValues(&amp;firstString, &amp;secondString)</pre><p><em>&lt;T&gt; </em>is called <strong>a type parameter list. </strong>It can have single or multiple parameters</p><pre>func someFunc&lt;<strong>T</strong>, <strong>U</strong>, <strong>V</strong>&gt;(_ first: <strong>T</strong>, _ second: <strong>U</strong>) -&gt; <strong>V</strong> { ... }</pre><p>Generics can also be used when defining a class, structure, or enum</p><pre>// <strong>Generic custom type</strong></pre><pre>struct Stack&lt;<strong>Element</strong>&gt; {<br>    var items = [<strong>Element</strong>]()</pre><pre>    mutating func push(_ item: <strong>Element</strong>) {<br>        items.append(item)<br>    }</pre><pre>    mutating func pop() -&gt; <strong>Element</strong> {<br>        return items.removeLast()<br>    }<br>}</pre><pre>var stringStack = Stack<strong>&lt;String&gt;</strong>()<br>stringStack.push(&quot;one&quot;)<br>stringStack.push(&quot;two&quot;)</pre><pre>var intStack = Stack<strong>&lt;Int&gt;</strong>()<br>intStack.push(1)<br>intStack.push(2)</pre><p>When extending a generic custom type, the type parameter list should be omitted. All type parameters are taken from the initial type declaration</p><pre><strong>extension</strong> Stack {<br>    var topItem: <strong>Element</strong>? {<br>        return items.isEmpty ? nil : items[items.count - 1]<br>    }<br>}</pre><p>For specifying that a type parameter must<strong> inherit from </strong>a specific<strong> class</strong> or <strong>conform to</strong> a particular <strong>protocol</strong>, there should be used <strong>type constraints</strong></p><pre>func someFunc&lt;<strong>T: SomeClass</strong>, <strong>U: SomeProtocol</strong>&gt;(someT: <strong>T</strong>, someU: <strong>U</strong>) {     <br>    ... <br>}</pre><p>Type constraints, themselves, make generic types more specific. As a result, it allows using code that requires some specific compatibilities</p><pre>func findIndex&lt;<strong>T:</strong> <strong>Equatable</strong>&gt;(of valueToFind: <strong>T</strong>, in array: [<strong>T</strong>]) -&gt; Int? {<br>    for (index, value) in array.enumerated() {<br>        // <strong>requires conformance to</strong> <strong>Equatable<br>        </strong>if value <strong>==</strong> valueToFind { <br>            return index<br>        }<br>    }<br>    return nil<br>}</pre><p>For defining a generic protocol, instead of a type parameter list, there should be declared <strong>associated types</strong></p><pre>// <strong>Generic protocol</strong></pre><pre>protocol SomeProtocol {<br>    <strong>associatedtype</strong> T<br>    func someFunc(_ value: T)<br>    <br>    <strong>associatedtype</strong> U<br>    func anotherFunc(_ value: U)<br>}</pre><p>When conforming to that protocols, types (structures, classes, or enums) may specify which exact type should replace a protocol associated type. To make it explicitly they use <em>typealias</em></p><pre>class SomeClass: SomeProtocol {<br>    <strong>typealias</strong> T = Int<br>    func someFunc(_ value: Int) { print(value) }<br>    <br>    <strong>typealias</strong> U = String<br>    func anotherFunc(_ value: String) { print(value) }<br>}</pre><p>However, <em>typealias </em>can be easily omitted. And then Swift infers associated types implicitly</p><pre>class SomeClass: SomeProtocol {<br>    func someFunc(_ value: Int) { print(value) }<br>    func anotherFunc(_ value: String) { print(value) }<br>}</pre><p>Moreover, associated types can be replaced with generic type parameters when adopting a protocol</p><pre>protocol SomeProtocol {<br>    associatedtype <strong>U</strong><br>    func someFunc(_ value: <strong>U</strong>)<br>}</pre><pre>class SomeClass<strong>&lt;T&gt; </strong>{ }</pre><pre>extension SomeClass: SomeProtocol {<br>    func someFunc(_ value: <strong>T</strong>) { }<br>}</pre><p>Associated types also support constraints based on conformance to a protocol or inheritance from a class</p><pre>protocol SomeProtocol {<br>    <strong>associatedtype</strong> T: AnotherProtocol<br>    func someFunc(_ value: T)<br>}</pre><h3>Generic Where Clause</h3><p>Generic<em> where </em>clause allows setting requirements on generic type parameters or associated types. The requirements can be the following: types must conform to a protocol, types must inherit from a class, and types must be the same or equal to a specific type</p><p><em>where </em>clause stays before the opening curly brace of a type or a function body</p><pre>// <strong>&quot;Conformance to a protocol&quot; example</strong><br>class SomeClass&lt;T&gt; <strong>where T: SomeProtocol</strong> { }</pre><pre>...</pre><pre>// <strong>&quot;Inheritance from a class&quot; example</strong><br>protocol SomeProtocol {<br>    associatedtype U <strong>where U: SomeClass</strong><br>}</pre><pre>...</pre><pre>// &quot;<strong>Types must be the same or equal to a specific type&quot; example<br></strong>//<strong> U is associated type<br></strong>func someFunc&lt;T1: SomeProtocol, T2: SomeProtocol&gt;(t1: T1, t2: T2) <strong>where T1.U == T2.U, T1.U == Int</strong> { }</pre><p><em>where </em>clause can also be used when extending a generic custom type or a protocol. In this case, the extension is available only when the type satisfies all requirements</p><pre><strong>extension</strong> Stack <strong>where Element: Equatable</strong> {<br>    func isTop(_ item: Element) -&gt; Bool {<br>        guard let topItem = items.last else {<br>            return false<br>        }<br>        return item == topItem<br>    }<br>}</pre><h3>Under the Hood</h3><p><strong>Important. </strong>Before reading the text below, take a look at <a href="https://medium.com/@maxim.kryloff/swift-method-dispatch-4ac7efab0388">Swift. Method Dispatch</a></p><p>There are two ways of working with generics in Swift: <strong>runtime way </strong>(boxing of generic values at runtime) and <strong>compile-time way </strong>(generic code turns into specific code for a particular type at compile-time, it is also called generic <strong>specialization</strong>)</p><h3>Runtime Way</h3><p>When following this way, Swift creates a <strong>single block of</strong> generic <strong>code</strong> for any type <em>T</em>. No matter what the initial type is, the value is passed into the generic function additionally with type metadata</p><pre>func <strong>test&lt;T&gt;</strong>(value: <strong>T</strong>) -&gt; <strong>T</strong> {<br>    let copy = value<br>    print(copy)<br>    return copy<br>}</pre><pre>// <strong>kind of runtime</strong></pre><pre>let myStruct = MyStruct()<br><strong>test</strong>(value: myStruct, metadata: <strong>MyStruct.metadata</strong>)<br>// <strong>muStruct value is stored in value buffer</strong></pre><p>But because different types (value and reference) behave differently, Swift uses a <strong>value buffer</strong> for storing their values, and <strong>Value Witness Table</strong> for having an ability to allocate memory on the heap for them, and to copy, move, and destroy their values through a single interface</p><p>Swift builds VWT for any type at compile-time</p><p>When <em>MyStruct</em> is generic itself, it gets more challenging to determine the type metadata because <em>MyStruct&lt;Int&gt; </em>and <em>MyStruct&lt;String&gt;</em> are different on any level of the program. And they also have different VWTs</p><p>In this case, Swift builds <strong>a metadata pattern</strong> based on the structure metadata. Then it combines the pattern with <em>T </em>metadata for getting the result information about the type, and also for having correct VWT</p><pre>// <strong>kind of runtime</strong></pre><pre>func test&lt;T&gt;(value: MyStruct&lt;T&gt;, tMetadata: T.Type) {<br>    let myStructMetadata =     <br>        <strong>get_generic_metadata</strong>(MyStruct.<strong>metadataPattern</strong>, <strong>tMetadata</strong>)  <br>}</pre><pre>let myStruct = MyStruct&lt;Int&gt;()<br><strong>test</strong>(value: myStruct, tMetadata: <strong>Int.metadata</strong>)</pre><p>When using constraints, Swift passes additional information about the constraint types to the function</p><pre>func compareAndDraw&lt;<strong>T</strong>&gt;(first: T, second: T)<br><strong>where T: Equatable, T: Drawable</strong> {<br>    if first <strong>==</strong> second { // <strong>Equtable</strong><br>        first.<strong>draw() </strong>    // <strong>Drawable</strong><br>        second.<strong>draw()</strong>    // <strong>Drawable</strong><br>    }<br>}</pre><pre>compareAndDraw(first: MyStruct(), second: MyStruct())</pre><p>In this case, for computing the function at runtime, there should be known pointers to <em>== </em>and <em>draw() </em>methods of <em>MyStruct</em>. For having those pointers, Swift passes Protocol Witness Table of <em>Equatable </em>and <em>Drawable</em> as additional parameters into the function</p><pre>// <strong>kind of runtime</strong></pre><pre>compareAndDraw(first: MyStruct(),<br>               second: MyStruct(),<br>               metadata: MyStruct.metadata,<br>               myStructIsEquatable: <strong>Equatable.pwt</strong>,                <br>               myStructIsDrawable: <strong>Drawable.pwt</strong>)</pre><p>The runtime way is less efficient than the compile-time one. Swift follows this way when it can’t determine a particular type to substitute for a generic one within the compilation process (e.g., the type is defined in another module)</p><h3>Compile-time Way or Specialization</h3><p>The compile-time way is a quite efficient optimization of generic code</p><p>Swift creates a separate function for each particular type during the compilation process, binding <em>T</em> with that type. It is called <strong>static polymorphism </strong>(or <strong>parametric polymorphism</strong>)</p><pre>func isEqual<strong>&lt;T: Equatable&gt;</strong>(first: <strong>T</strong>, second: <strong>T</strong>) -&gt; Bool {<br>    return first == second<br>}</pre><pre>isEqual(first: 1, second: 2)<br>isEqual(first: &quot;one&quot;, second: &quot;one&quot;)<br>isEqual(first: MyStruct(), second: MyStruct)</pre><pre>// <strong>kind of runtime</strong></pre><pre>isEqual(first: <strong>Int</strong>, second: <strong>Int</strong>) { ... }<br>isEqual(first: <strong>String</strong>, second: <strong>String</strong>) { ... }<br>isEqual(first: <strong>MyStruct</strong>, second: <strong>MyStruct</strong>) { ... }</pre><p>If the compile-time way is available, using generic code, constrained by protocols, is more efficient than using the protocols directly because:</p><ul><li>there are no existential containers and, as a result, no extra heap allocations (if using structures)</li><li>instead of having Table Dispatch any time when calling a protocol method, there can be used Direct Dispatch, because of taking a structure as a parameter type</li></ul><pre>function draw(copy: <strong>Drawable</strong>) {<br>    copy.draw()<br>}</pre><pre>draw(copy: MyStruct()) // <strong>always Table Dispatch (PWT)</strong></pre><pre>// <strong>vs</strong></pre><pre>function draw<strong>&lt;T: Drawable&gt;</strong>(copy: T) {<br>    copy.draw()<br>}</pre><pre>draw(copy: MyStruct()) // <strong>Direct Dispatch<br>// because at runtime it will be<br></strong>// <strong>function draw(copy: MyStruct) { ... }</strong></pre><p>Moreover, when applying compile-time way optimizations, Swift can do inlining code to decrease the number of function calls</p><pre>function draw(copy: MyStruct) {<br>    copy.draw()<br>}</pre><pre>// <strong>before inlining code<br></strong>draw(copy: MyStruct())</pre><pre><strong>// after inlining code<br></strong>MyStruct().draw()</pre><p>Along with generic functions, compile-time way optimizations can also be applied to generic types</p><pre>struct Pair {<br>    var first: <strong>Drawable</strong><br>    var second: <strong>Drawable</strong><br>}</pre><pre>Pair(first: MyStruct(), second: MyStruct())</pre><pre>// <strong>vs</strong></pre><pre>struct Pair<strong>&lt;T: Drawable&gt;</strong> {<br>    var first: <strong>T</strong><br>    var second: <strong>T</strong><br>}</pre><pre>Pair(first: MyStruct(), second: MyStruct()) // <strong>more efficient</strong></pre><p>Again, when using a generic type, there are no existential containers because Swift at compile-time can determine a particular type that is stored inside a generic structure instance, which is being created. And that type doesn’t change at runtime</p><p>In generic types, because <em>MyStruct </em>is a structure, <em>first </em>and<em> second </em>properties are stored inline on the stack, as the whole enclosing structure <em>Pair</em>. No heap allocations there. Static Dispatch is used when calling methods of <em>first</em> and <em>second</em>, or <em>Pair</em> structure itself</p><p>The compile-time way is available when Swift has a type definition during the compilation of generic code. It happens if both type definition and generic code are placed in the same file. If they are separated from each other but still placed in the same module, applying <strong>whole module optimization </strong>(is on by default since Xcode 10) enables considering the whole module as one file, and as a result, having generic specialization within the module</p><h3>Resources</h3><ul><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Generics.html">https://docs.swift.org/swift-book/LanguageGuide/Generics.html</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2016/416/">https://developer.apple.com/videos/play/wwdc2016/416/</a></li><li><a href="https://www.youtube.com/watch?v=ctS8FzqcRug">https://www.youtube.com/watch?v=ctS8FzqcRug</a></li><li><a href="https://habr.com/ru/post/451704/">https://habr.com/ru/post/451704/</a></li><li><a href="https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst">https://github.com/apple/swift/blob/master/docs/OptimizationTips.rst</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4faa1cb0b930" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Method Dispatch]]></title>
            <link>https://maxim-kryloff.medium.com/swift-method-dispatch-4ac7efab0388?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac7efab0388</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 11:20:57 GMT</pubDate>
            <atom:updated>2021-05-29T16:37:24.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p><em>…the more restrictive code comes to the compiler, the more performant it is at runtime</em></p><p>Method Dispatch is all about telling CPU where in memory it can find executable code for a particular method call</p><h3>Direct Dispatch</h3><p>Direct Dispatch is also called Static Dispatch</p><p>The compiler <strong>does</strong> <strong>know</strong> which executable code should be used</p><p>Direct Dispatch is the fastest style of the method dispatch. It requires a minimal set of assembly instructions to get executable code. Moreover, the compiler can apply optimizations, like inlining code</p><pre>// <strong>Inlining code</strong></pre><pre>struct Point {<br>    let x: Int<br>    let y: Int</pre><pre>    func draw() {<br>        print(&quot;x: \(x), y: \(y)&quot;)<br>    }<br>}</pre><pre>func draw(point: Point) {<br>    point.draw()<br>    print(&quot;point is drawn&quot;)<br>}</pre><pre>// ... <strong>initial code</strong><br>let p1 = Point(x: 0, y: 0)<br>draw(point: p1)</pre><pre>// ... <strong>after inlining code<br></strong>let p1 = Point(x: 0, y: 0)<br>p1.draw()<br>print(&quot;point is drawn&quot;)</pre><pre>// ... <strong>after inlining code<br></strong>let p1 = Point(x: 0, y: 0)<br>print(&quot;x: \(p1.x), y: \(p1.y)&quot;)<br>print(&quot;point is drawn&quot;)</pre><p>However, this is the most restrictive way. It doesn’t allow things like polymorphism</p><h3>Table Dispatch</h3><p>Table Dispatch is the most common method of dispatch among compiled languages, such as C#, Java, and Swift</p><p>The compiler <strong>does not know</strong> which executable code should be used for a particular method call. This decision is taken at runtime</p><pre>class Animal {<br>    func makeNoise() { }<br>}</pre><pre>class Cat: Animal {<br>    override func makeNoise() { print(&quot;meow&quot;) }<br>}</pre><pre>class Fox: Animal {<br>    override func makeNoise() { print(&quot;.. what does the fox say?&quot;) }<br>}</pre><pre>let animals: [Animal] = [Cat(), Cat(), Fox(), Fox(), Cat()]</pre><pre>for animal in animals { animal<strong>.makeNoise()</strong> } // <strong>polymorphism</strong></pre><p>Classes have tables, called <strong>Virtual Tables</strong>. Each table has an array of function pointers to methods of the corresponding class</p><p>Every subclass has <strong>its own copy</strong> of Virtual Table with different function pointers to those methods, which are overridden. As a subclass adds a new method to its definition, the method is appended to the end of the corresponding table</p><p>The compiler builds the tables, and at runtime, the tables are used to determine which method should be called</p><pre>class ParentClass {<br>    func method1() { }<br>    func method2() { }<br>}</pre><pre>class ChildClass: ParentClass {<br>    <strong>override</strong> func method2() { }<br>    func method3() { }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3cCWgiST02MJHeMrIZ4AQ.png" /></figure><pre>let obj = ChildClass()<br>obj.method2()</pre><p>Each class instance has a property <em>type</em> (or <em>isa</em> in Objective-C, each NSObject has this property). The tables are stored in some static memory region and can be taken by this property</p><p>When <em>method2</em> is called, the process will:</p><ol><li>take Virtual Table for the object of 0xB00 (<em>ChildClass</em>) by its property <em>type</em></li><li>take the function pointer of <em>method2</em> from the table (the pointer is taken by index 1). Thus, the function pointer is 0x222</li><li>jump to the address 0x222, that contains the executable code</li></ol><p>Each method in such tables isn’t aware of <em>self</em> (<em>obj</em>). At runtime <em>self </em>(<em>obj</em>) is passed as a parameter when calling the method</p><pre>//<strong> ... kind of runtime<br></strong>method2(obj)</pre><p>Table Dispatch is still good but less efficient than the previous one because it takes three additional steps (take the table, take the function address, jump to that address to get executable code). And also, it is less efficient because the compiler applies <strong>no optimizations</strong></p><h3>Protocol Witness Tables</h3><p><strong>Virtual Tables</strong> are used when using<strong> classes</strong> and <strong>inheritance</strong>, and <strong>Protocol</strong> <strong>Witness Tables</strong> — when conforming to <strong>protocols</strong></p><p>The problem is that structures don’t support inheritance because they don’t have Virtual Tables. But conforming to protocols allows them to use Table Dispatch and polymorphism. However, instead of Virtual Tables, they get Protocol Witness Tables</p><pre>// <strong>Polymorphism without classes and inheritance</strong></pre><pre><strong>protocol</strong> Noisable {<br>    func makeNoise()<br>}</pre><pre><strong>struct</strong> Cat: Noisable {<br>    func makeNoise() { print(&quot;meow&quot;) }<br>}</pre><pre><strong>struct</strong> Fox: Noisable {<br>    func makeNoise() { print(&quot;.. what does the fox say?&quot;) }<br>}</pre><pre>let noisers: [Noisable] = [Cat(), Cat(), Fox(), Fox(), Cat()]</pre><pre>for noiser in noisers { noiser.<strong>makeNoise()</strong> } // <strong>polymorphism</strong></pre><p>Each type (value and reference) that conforms to a protocol has its own Protocol Witness Table. The table has pointers to those methods of the type that are required by the protocol</p><p>Structures and classes that conform to a protocol can have different sizes. To store them in<strong> the same array</strong> (like <em>noisers</em>) or in<strong> the same type property</strong>, or to pass them as an <strong>argument </strong>to<strong> the same function</strong>, and also to find corresponding Protocol Witness Table for each of them, Swift uses <strong>existential containers</strong></p><p>An existential container is a structure, that always has a <strong>fixed size</strong> (in x64, it is 5 * 64 = <strong>320 bit </strong>or five machine words), and consists of three parts: reference to Value Witness Table (VWT), a reference to Protocol Witness Table (PWT), and a value buffer to store an instance itself</p><p><strong>The buffer</strong> stores an initial instance. It takes three machine words. If the instance doesn’t fit the buffer size (takes more than three machine words or more than 3 * 64 bit), it gets placed on the heap via VWT (see below), and the buffer contains a reference to that instance. But if it does, the buffer stores the value directly (the value is placed on the stack). However, it is only about value types. For reference types, the buffer stores a reference anyway</p><p><strong>Value Witness Table </strong>is an abstract representation of instance life cycle manipulations. Since different types (value and reference) have different mechanisms of copying, moving, and destroying their values, VWT is used to abstract from the implementation of the current instance and do those manipulations through a single interface. It has the following properties and methods: <em>size </em>(initial instance size), <em>copy</em>,<em> move</em>,<em> destroy</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AqAESRcYSF9cjLPCzq71w.png" /></figure><p>Also, <strong>VWT </strong>has methods <em>allocate, </em>and <em>deallocate </em>for <strong>placing the instance on the heap</strong> if it doesn’t fit the value buffer size and <strong>removing the instance from the heap</strong> accordingly</p><p><strong>Protocol Witness Table</strong>, again, stores pointers to those methods of the instance type that are required by the protocol</p><p>Due to each existential container has a fixed size, no matter what instance type is stored there, the container itself is placed on the stack</p><p>Using POP (Protocol-Oriented Programming) and structures are better than using OOP (Object-Oriented Programming) and classes from the performance point of view — when using structures, we can have polymorphism (because of POP), but avoid reference counting and extra heap allocations (because of structures)</p><h3>Message Dispatch</h3><p>Message Dispatch is the most dynamic style of the method dispatch. It’s a cornerstone of Cocoa development. It’s used by KVO, CoreData, UIAppearance…</p><p>The compiler, in this case, also <strong>does not know</strong> which executable code should be used for a particular method call</p><p>A key point of Message Dispatch is modifying the dispatch behavior at runtime, applying method swizzling (exchanging method invocations at runtime) or isa-swizzling (exchanging an object type at runtime)</p><p><strong>Method Swizzling </strong>allows exchanging the implementation of two class methods at runtime. <strong>This will affect every instance of a modified class</strong>, which was or will be created. If you have <em>methodA</em> and <em>methodB</em>, method swizzling allows you to call the implementation of <em>methodB</em> when calling <em>methodA</em>, and vice versa. It could be helpful for setting some default behavior to a class, avoiding inheritance. But Swift can use protocols for these purposes (Objective-C cannot)</p><p><strong>Isa-Swizzling </strong>allows exchanging the type of a given single object with another type at runtime. If you have two classes: <em>ClassA</em> and <em>ClassB</em>, you can create an instance of <em>ClassA</em>, then at runtime change its type to <em>ClassB</em> (change property <em>isa)</em>, then call some method of <em>ClassB</em>, and then switch the type back to <em>ClassA</em></p><pre>class ParentClass {<br>    <strong>dynamic</strong> func method1() { }<br>    <strong>dynamic</strong> func method2() { }<br>}</pre><pre>class ChildClass: ParentClass {<br>    <strong>override</strong> func method2() { }<br>    <strong>dynamic</strong> func method3() { }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TndUzBnSXkJlXc7HN3jWg.png" /></figure><p>Swift builds this hierarchy as a tree structure and puts it into some static memory region. When a message is dispatched (<em>method2 </em>is called), the process will:</p><ol><li>take the hierarchy tree</li><li>try to find the function pointer of <em>method2</em> in <em>ChildClass</em> table</li><li>if the function pointer is found, jump to the address to get executable code</li><li>else go to <em>ParentClass</em> (super of <em>ChildClass</em>) and repeat 2–4</li><li>do this until the function pointer is found or the root class of the hierarchy is reached</li></ol><p>For the first method call, it’s slower than Table Dispatch because it goes through the tree to find the corresponding function pointer. But after that, Swift caches the found table, and the second method call will take Table Dispatch time</p><p>Swift uses the Swift runtime whenever it’s possible. It allows making optimizations when preparing code for runtime. Thus, at runtime, the code is more efficient. Swift only opts for a dynamic dispatch and Objective-C runtime if it has no other choice</p><p>Objective-C uses Message Dispatch in most cases, but developers sometimes can use Direct Dispatch there</p><p>Where a method is declared determines what the method dispatch is used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Khwrb71pU6yGotvEz7DmJg.png" /></figure><p>Inheritance from <em>NSObject</em> makes a class “dynamic message dispatchable”, but methods in initial declarations are called via Table Dispatch</p><p><strong>Object type determines which type of dispatch will be used on a method call. </strong>If the type is a protocol, then look at the protocol row in the table. If it casts the object to its class type or structure type, then look at the class or value type rows in the table</p><pre>class A {<br>    func doAction() { }                      // <strong>table dispatch</strong><br>}</pre><pre>class B: A {<br>    final override func doAction() { }       // <strong>static dispatch</strong><br>}</pre><pre>let a: A = A()<br>a.doAction()     // <strong>will be called via table dispatch</strong></pre><pre>let b1: A = B()<br>b1.doAction()    // <strong>will be called via table dispatch</strong></pre><pre>let b2: B = B()<br>b2.doAction()    // <strong>will be called via static dispatch</strong></pre><h4>final</h4><p>The <em>final</em><strong> </strong>keyword enables Static Dispatch on a method defined in a class. This keyword removes the possibility of any dynamic behavior and also hides the method from Objective-C runtime. It doesn’t generate a selector. Applying <em>final</em> to a class denies inheritance from the class and also makes class methods to be called via Static Dispatch. Using this keyword allows the compiler to make some optimizations for increasing performance. It can be applied to classes only</p><pre>// <strong>denies any inheritance from the class<br>final</strong> class Animal {<strong><br>    </strong>// <strong>makes the method called via static dispatch<br>    final</strong> func move() { }<strong><br></strong>}</pre><h4>dynamic</h4><p>The <em>dynamic</em> keyword enables Message Dispatch on a method defined in a class. This keyword implicitly marks the method as <em>@objc</em>, which means the method is visible for Objective-C runtime. Swift doesn’t say that <em>dynamic</em> is available for classes only, <strong>but </strong>structures and enumerations don’t support inheritance. The runtime doesn’t have to figure out which implementation it needs to use. Thus, at runtime for structures and enums <em>dynamic</em> doesn’t work. Using this keyword can make your code less performant</p><pre>class Animal {<br>    // <strong>message dispatch at Objective-C runtime<br></strong>    <strong>dynamic</strong> func move() { }<strong><br></strong>}</pre><h4>@objc</h4><p>The <em>@objc</em><strong> </strong>keyword<strong> does not</strong> alter the method dispatch. It just makes the method visible for Objective-C runtime. The most common use of <em>@objc </em>is making selectors. And also, using <em>@objc</em> allows overriding methods declared in class extensions (by default, it is impossible because of Static Dispatch)</p><pre>class Animal {<br>    @objc func move() { } // <strong>is visible at Objective-C runtime</strong><br>}</pre><pre>class Animal { }</pre><pre><strong>extension</strong> Animal {<br>    <strong>@objc</strong> func move() { }<br>}</pre><pre>class Lion: Animal {<br>    <strong>override</strong> func move() { }<br>}</pre><h4>@nonobjc</h4><p>The<strong> </strong><em>@nonobjc</em> keyword <strong>does</strong> alter the method dispatch. It can be used to disable Message Dispatch and to make the method invisible for Objective-C runtime. It seems <strong>there is no difference</strong> between <em>@nonobj</em> and <em>final</em>, so using <em>final</em> makes code more clear</p><h4>@objc final</h4><p>Keyword<strong> </strong><em>@objc final</em><strong> </strong>enables Direct Dispatch on a method and registers the method selector at Objective-C runtime. The keyword allows the method to respond when performing a selector or other Objective-C features, along with giving the performance of Direct Dispatch</p><pre>class Animal {<br>    // <strong>direct dispatch, visible for Objective-C runtime</strong><br>    <strong>@objc final</strong> func move() { }<br>}</pre><p>If a property is observed with KVO and that property is upgraded to Direct Dispatch, the code will still compile, but the dynamically generated KVO method won’t be triggered</p><h3>SR-103 (Swift bug, protocols)</h3><pre>protocol Greetable {<br>    func sayHi()<br>}</pre><pre><strong>extension</strong> Greetable {<br>    func sayHi() {<br>        print(&quot;from protocol&quot;)<br>    }<br>}</pre><pre>func greetings(greeter: Greetable) {<br>    greeter.sayHi()<br>}</pre><pre>class Person: Greetable { }</pre><pre>class Employee: Person {<br>    func sayHi() {<br>        print(&quot;from employee&quot;)<br>    }<br>}</pre><pre>greetings(greeter: Employee())<br>// <strong>from protocol, however Employee has own implementation</strong></pre><h3>Resources</h3><ul><li><a href="https://www.rightpoint.com/rplabs/switch-method-dispatch-table">https://www.rightpoint.com/rplabs/switch-method-dispatch-table</a></li><li><a href="https://stackoverflow.com/questions/38877465/are-method-swizzling-and-isa-swizzling-the-same-thing/38878119#38878119">https://stackoverflow.com/questions/38877465/are-method-swizzling-and-isa-swizzling-the-same-thing/38878119#38878119</a></li><li><a href="https://medium.com/better-programming/swift-why-you-should-avoid-using-default-implementations-in-protocols-eeffddbed46d">https://medium.com/better-programming/swift-why-you-should-avoid-using-default-implementations-in-protocols-eeffddbed46d</a></li><li><a href="https://medium.com/@PavloShadov/https-medium-com-pavloshadov-swift-protocols-magic-of-dynamic-static-methods-dispatches-dfe0e0c85509">https://medium.com/@PavloShadov/https-medium-com-pavloshadov-swift-protocols-magic-of-dynamic-static-methods-dispatches-dfe0e0c85509</a></li><li><a href="https://cocoacasts.com/what-does-the-dynamic-keyword-mean-in-swift-3/">https://cocoacasts.com/what-does-the-dynamic-keyword-mean-in-swift-3/</a></li><li><a href="https://habr.com/ru/post/473798/">https://habr.com/ru/post/473798/</a></li><li><a href="https://habr.com/ru/post/474558/">https://habr.com/ru/post/474558/</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2016/416/">https://developer.apple.com/videos/play/wwdc2016/416/</a></li><li><a href="https://www.youtube.com/watch?v=ctS8FzqcRug">https://www.youtube.com/watch?v=ctS8FzqcRug</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac7efab0388" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Closures]]></title>
            <link>https://maxim-kryloff.medium.com/swift-closures-2fcad25790a3?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fcad25790a3</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 05:40:10 GMT</pubDate>
            <atom:updated>2021-05-29T16:37:01.005Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><h3>In-out Parameters</h3><p>Function parameters are <strong>constant</strong> by default</p><p><strong>In-out </strong>parameters are used to modify parameter values. So, after a function returns, a variable that is passed as <em>&amp;</em>variable will have the modified value</p><pre>var num1 = 3<br>var num2 = 5</pre><pre>func swap(_ num1: <strong>inout</strong> Int, _ num2: <strong>inout</strong> Int) {<br>    let temp = num1<br>    num1 = num2<br>    num2 = temp<br>}</pre><pre>swap(<strong>&amp;</strong>num1, <strong>&amp;</strong>num2) // <strong>num1 = 5, num2 = 3</strong></pre><p>In-out parameters are passed as follows:</p><ol><li>when a function is called, the value of the argument is copied</li><li>in the function body, the copy is modified</li><li>when the function returns, the copy is assigned to the original argument</li></ol><p>It is called <strong>copy-in copy-out</strong> behavior</p><h3>Memory Safety Problem</h3><p>In most cases, Swift manages memory automatically. Most of the time, there is no need to care about accessing memory at all. And even if there is conflicting access to memory from within a <strong>single thread</strong>, Swift guarantees that it will go along with a compile-time or runtime error</p><p>Conflicting access can occur when one part of the code changes a memory region, which is being updated by another part of the code at the same time. It can happen within a <strong>single thread</strong>. So, it is not about concurrency</p><p>Characteristics of memory access, which should be considered when telling about the conflicts:</p><ul><li>whether the<strong> memory access</strong> is <strong>read</strong> or <strong>write</strong></li><li>the duration of <strong>memory access</strong> is <strong>instantaneous</strong> or <strong>long-term</strong></li><li>the <strong>location in memory</strong></li></ul><p>Access is instantaneous if other code <strong>can’t</strong> run after the access starts but before it ends. Most memory accesses are instantaneous</p><p>Access is long-term if other code <strong>can</strong> run when the access starts but before it ends. It’s called <strong>overlap.</strong> Long-term access can overlap with other long-term or instantaneous accesses</p><p>The conflict happens <strong>if</strong> there are two or more accesses, <strong>and</strong> at least one of them is write, <strong>and </strong>all of them refer to the same memory region, <strong>and </strong>their durations overlap</p><p>Overlapping accesses appear primarily in code that uses <strong>in-out parameters</strong> in functions, and <strong>mutating methods of a structure</strong></p><p>A function has long-term write access to all of its in-out parameters. Long-term access starts when all non-in-out parameters are evaluated and ends when the entire function ends</p><p>The first consequence is that it is impossible to have access to variables, which are passed as in-out parameters, from the outside scope during the function execution</p><pre>var <strong>stepSize</strong> = 1</pre><pre>func increment(_ number: inout Int) {<br>    number += <strong>stepSize</strong><br>}</pre><pre>increment(&amp;<strong>stepSize</strong>) // <strong>the runtime error</strong></pre><pre>// <strong>number and stepSize refer to the same variable<br></strong>// <strong>in-out captures &amp;stepSize for having write access,<br></strong>// <strong>and the function captures stepSize for having read access</strong></pre><pre>// <strong>A possible solution</strong></pre><pre>var stepSize = 1<br>var <strong>stepSizeCopy</strong> = stepSize</pre><pre>func increment(_ number: inout Int) {<br>    number += stepSize<br>}</pre><pre>increment(&amp;<strong>stepSizeCopy</strong>)<br>stepSize = <strong>stepSizeCopy</strong></pre><p>Another consequence of long-term write access to in-out parameters is that passing the same variable as multiple in-out argument of the same function produces a conflict</p><pre>func balance(_ x: inout Int, _ y: inout Int) {<br>    let sum = x + y<br>    x = sum / 2<br>    y = sum - x<br>}</pre><pre>var firstPlayerScore = 42<br>var secondPlayerScore = 30</pre><pre>balance(&amp;firstPlayerScore, &amp;secondPlayerScore)<br>// <strong>ok<br></strong>balance(&amp;<strong>firstPlayerScore</strong>, &amp;<strong>firstPlayerScore</strong>)<br>// <strong>the compile-time error</strong></pre><p>A mutating method of a structure has long-term write access to <em>self </em>within the whole method call. Long-term access to <em>self</em> starts when the mutating method starts and ends when the entire method ends (<em>self</em> behaves like <em>inout</em>)</p><pre>struct Player {<br>    var health: Int<br>    mutating func shareHealth(with player: inout Player) {<br>        player.health = health<br>    }<br>}</pre><pre>var p1 = Player(health: 100)<br>var p2 = Player(health: 200)</pre><pre>p2.shareHealth(with: &amp;p1) // <strong>ok<br>p2</strong>.shareHealth(with: &amp;<strong>p2</strong>) // <strong>the compile-time error</strong></pre><p>In terms of <strong>tuples</strong>, <strong>structures</strong>, and <strong>enums </strong>(<strong>value types</strong>), access to a single property means access to the whole structure</p><pre>var playerInfo = (health: 10, energy: 20)         // <strong>tuple</strong><br>balance(&amp;<strong>playerInfo</strong>.health, &amp;<strong>playerInfo</strong>.energy)<br>// <strong>the compile-time error</strong></pre><pre>var player = Player(health: 200, energy: 150)     // <strong>structure</strong><br>balance(&amp;<strong>player</strong>.health, &amp;<strong>player</strong>.energy)         <br>// <strong>the compile-time error</strong></pre><p>But in practice, most accesses to structure properties can overlap safely because they occur with local function variables instead of global ones. In this case, Swift can say for sure that the accesses are safe</p><pre>func someFunc() {<br>    <strong>var</strong> playerInfo = (health: 10, energy: 20)<br>    balance(&amp;playerInfo.health, &amp;playerInfo.energy)<br>}<br>someFunc() // <strong>ok</strong></pre><p>Swift can confirm that overlapping access to structure is safe if the following requirements are satisfied:</p><ul><li>it’s accessing <strong>only </strong>to <strong>stored properties</strong> of the instance, but not computed or class ones</li><li>the structure is a value of a <strong>local variable</strong>, but not a global one</li><li>the structure is either<strong> not captured by any closure</strong>, or it’s captured only by a<strong> non-escaping</strong> one</li></ul><p>If a nested <strong>escaping</strong> closure captures an in-out parameter, Swift throws a compile-time error</p><pre>func someFunction(<strong>a</strong>: <strong>inout</strong> Int) -&gt; () -&gt; Int {<br>    return { () in return <strong>a</strong> + 1 } // <strong>the compile-time error<br></strong>}</pre><pre>// <strong>Possible solutions</strong></pre><pre>// <strong>capture list<br></strong>func someFunction(a: inout Int) -&gt; () -&gt; Int {<br>    return { <strong>[a]</strong> () in return <strong>a</strong> + 1 }<strong><br></strong>}</pre><pre>// <strong>local variable<br></strong>func someFunction(queue: DispatchQueue, x: inout Int) {<br>    var <strong>localX</strong> = x<br>    defer { x = <strong>localX</strong> }</pre><pre>    queue.async { someMutatingOperation(&amp;<strong>localX</strong>) }<br>    queue.sync {} // <strong>queue should be serial</strong><br>}</pre><p>By default, when a closure captures a variable from the surrounding context and changes the value inside, then the variable will also be changed in outside scope. No matter whether it is a value or reference type</p><pre>struct Calculator {<br>    var a: Int<br>    var b: Int</pre><pre>    var sum: Int {<br>        return a + b<br>    }<br>}</pre><pre>var calculator = Calculator(a: 3, b: 5)</pre><pre>let closure = {<br>    calculator = Calculator(a: 30, b: 50)<br>}</pre><pre>// <strong>Calculator(3, 5)<br></strong>closure()<br>// <strong>Calculator(30, 50)</strong></pre><p>The default behavior has a side effect if a variable gets changed in outside scope after the closure is defined but before it’s called. Then the closure will have the changed variable value</p><pre>var calculator = Calculator(a: 3, b: 5)</pre><pre>let closure = {<br>    print(calculator.sum)<br>}</pre><pre>calculator = Calculator(a: 30, b: 50)<br>closure()<br>// <strong>prints 80, but we wanted 8</strong></pre><p>To prevent the side effect, the closure must use a capture list. A <strong>capture list</strong> keeps immutable copies of variables (the copies are <strong>constant</strong>, an attempt to change them will produce a compile-time error)</p><pre>var calculator = Calculator(a: 3, b: 5)</pre><pre>let closure = { <strong>[calculator] </strong>in<br>    print(calculator.sum)<br>}</pre><pre>calculator = Calculator(a: 30, b: 50)<br>closure()<br>// <strong>prints 8</strong></pre><p>By default, if a class or structure method has an escaping closure, and the closure uses properties or methods of that class or structure, it is required to specify <em>self</em> explicitly (<em>self.classMethod()</em>). Otherwise, it will cause a compile-time error</p><p>Closures are reference types. They store strong references to the class instances that are captured from the surrounding context (no matter whether it is <em>self</em> or just a variable)</p><pre>class Animal {<br>    public let name: String</pre><pre>    init(name: String) {<br>        self.name = name<br>    }</pre><pre>    deinit {<br>        print(&quot;\(name) is deinited&quot;)<br>    }<br>}</pre><pre>class AnimalHandler {<br>    public var closure: (() -&gt; Void)?<br>   <br>    public func setPanda() {<br>        let <strong>panda</strong> = Animal(name: &quot;panda&quot;)<br>        closure = { print(<strong>panda</strong>.name) }<br>    }<br>}</pre><pre>let animalHandler = AnimalHandler()<br>animalHandler.setPanda()<br>animalHandler.closure = nil<br>// <strong>panda is deinited only when the closure is deinited</strong></pre><pre>class AnimalHandler {<br>    public var closure: (() -&gt; Void)?<br>   <br>    public func setPanda() {<br>        var panda: Animal? = Animal(name: &quot;panda&quot;)<br>        // <strong>capture list makes one more strong reference</strong><br>        closure = { <strong>[panda]</strong> in print(panda!.name) }<br>        panda = nil // <strong>nothing happens<br></strong>    }<br>}</pre><pre>let animalHandler = AnimalHandler()<br>animalHandler.setPanda()<br>animalHandler.closure = nil<br>// <strong>panda is deinited only when the closure is deinited</strong></pre><pre>class AnimalHandler {<br>    public var closure: (() -&gt; Void)?<br>   <br>    public func setPanda() {<br>        var panda: Animal? = Animal(name: &quot;panda&quot;)<br>        closure = { [<strong>weak</strong> panda] in print(panda!.name) }<br>        panda = nil // <strong>panda is deinited here<br></strong>    }<br>}</pre><pre>let animalHandler = AnimalHandler()<br>animalHandler.setPanda()</pre><p>For value types, a capture list makes an immutable <strong>copy</strong> of data, but for reference types, it makes <strong>one more </strong>strong<strong> reference </strong>by default if there are no <em>weak</em> or <em>unowned</em> words</p><p>A closure and its surrounding context are connected to each other. Let’s say that the closure has its own variables plus the surrounding context variables</p><p>If closure changes variables from the surrounding context, after calling the closure, the context will have updated values. And vice versa, if the context changes variables after defining the closure but before calling it, the closure will get updated values because both the context and the closure refer to the same context variables</p><p>A capture list in closures allows making own copies of data (value types) or own references to class instances (reference type) when the closure is defined. In this case, if the context changes or destructs the variables, the closure will still have its own copies</p><p>And if the closure is escaping (it is called after the function returns), it stores the context data even when the context doesn’t live anymore. Using escaping closures allows the context data to live till the closure is alive. But Swift also <strong>handles all memory management</strong> involved in <strong>disposing of variables</strong> when they are <strong>no longer needed</strong>. Thus, escaping closures store only those variables from the context that are really used</p><p><strong>Escaping</strong> closures (<em>@escaping</em>) require using <em>self</em> explicitly for both reference and value type. If self is an instance of a <strong>structure</strong> or an <strong>enumeration</strong>, the escaping closure <strong>can’t capture a mutable reference </strong>to <em>self</em>. Structures and enumerations don’t allow sharing mutability</p><pre><strong>class</strong> SomeClass {<br>    var x = 10<br>    func doSomething() {<br>        <strong>// ok because of class<br>        </strong>someFuncWith<strong>EscapingClosure</strong> { self.x = 100 } <strong><br>    </strong>}<br>}</pre><pre>// <strong>but</strong></pre><pre><strong>struct</strong> SomeStruct {<br>    var x = 10<br>    mutating func doSomething() {<br>        // <strong>the compile-time error because of structure<br>        </strong>someFuncWith<strong>EscapingClosure</strong> { self.x = 100 }<strong><br>    </strong>}<br>}</pre><p>If an escaping closure is used as a completion handler or just a part of an async operation, <strong>the best practice </strong>there is capturing <em>self</em> as <em>weak</em>. So, if the function is being executed for a long time, <em>weak</em> <em>self</em> allows disposing of resources captured by the closure before the async logic completely ends</p><p>E.g., the user leaves a screen that triggered an async function of a service. And <em>self</em> (of the service) is captured by an escaping closure inside the function. Having <em>weak self</em> there allows to free resources of the service before the whole async logic is completed</p><pre>// <strong>best practice</strong></pre><pre>class Service {<br>    var <strong>requestState</strong>: String = &quot;&quot;</pre><pre>    public func getData(callback: @escaping (_ data: Any) -&gt; Void) {<br>        <strong>requestState</strong> = &quot;request has been stared&quot;<br>        apiService.getDataFromServer() { <strong>[weak self] </strong>(data) in<br>            self?.<strong>requestState</strong> = &quot;request has been finished&quot;<br>            callback(data)<br>        }<br>    }<br>}</pre><p><strong>Advice: </strong>If a closure isn’t escaping, don’t think about memory leakages. Just use it and feel happy. But if it is, keep in mind memory leakage problems</p><h3><strong>Resources</strong></h3><ul><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Functions.html">https://docs.swift.org/swift-book/LanguageGuide/Functions.html</a></li><li><a href="https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID545">https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID545</a></li><li><a href="https://docs.swift.org/swift-book/LanguageGuide/MemorySafety.html">https://docs.swift.org/swift-book/LanguageGuide/MemorySafety.html</a></li><li><a href="https://marcosantadev.com/capturing-values-swift-closures/">https://marcosantadev.com/capturing-values-swift-closures/</a></li><li><a href="https://docs.swift.org/swift-book/LanguageGuide/Closures.html">https://docs.swift.org/swift-book/LanguageGuide/Closures.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fcad25790a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. ARC]]></title>
            <link>https://maxim-kryloff.medium.com/swift-arc-7a85e56283bb?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a85e56283bb</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 13:09:27 GMT</pubDate>
            <atom:updated>2021-05-29T16:36:42.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p>Automatic Reference Counting (ARC) is a <strong>compile-time</strong> mechanism that takes over memory management. This mechanism works <strong>only</strong> for objects that are stored on the heap (reference types)</p><p>Before ARC appeared, developers had to manage memory and objects lifetime manually. For these purposes, they used the following functions: <em>retain</em>, <em>release</em>,<em> </em>and <em>autorelease</em></p><p><em>retain</em><strong> </strong>is an instance method that makes reference count of the instance + 1</p><p><em>release</em><strong> </strong>is an instance method that makes reference count of the instance — 1. When the count reaches 0, it calls the instance method <em>dealloc</em> to dispose of the instance and free up memory on the heap</p><p><em>autorelease</em> is an instance method that adds the instance to an autorelease pool<strong> </strong>for having a deferred <em>release </em>call</p><p>Today, when code is being compiled, ARC inserts <em>retain</em>, <em>release</em>, and <em>autorelease </em>calls to the code automatically. And, roughly speaking, that is all that ARC does. However, it is smart enough to make it okay, avoiding unnecessary insertions. The code remains quite efficient. So, there is no need to think about manual reference management anymore</p><p>The critical point here is that ARC is namely a <strong>compile-time</strong> mechanism. So, it doesn’t manage memory at runtime or do some magic with the heap there</p><pre>class Person {<br>    public let name: String</pre><pre>    init(name: String) {<br>        self.name = name<br>        print(&quot;person is initialized&quot;)<br>    }</pre><pre>    deinit {<br>        print(&quot;person is reinitialized&quot;)<br>    }<br>}</pre><pre>var person1: Person?<br>var person2: Person?<br>var person3: Person?</pre><pre>person1 = Person(name: &quot;Maxim&quot;)<br>// <strong>person is initialized<br></strong>// <strong>retain(Person(Maxim)), 1 strong reference</strong></pre><pre>person2 = person1<br>// <strong>retain(Person(Maxim)), 2 strong references</strong></pre><pre>person3 = person1<br>// <strong>retain(Person(Maxim)), 3 strong references</strong></pre><pre>person1 = nil<br>// <strong>release(Person(Maxim)), 2 strong references</strong></pre><pre>person2 = nil<br>// <strong>release(Person(Maxim)), 1 strong reference</strong></pre><pre>person3 = nil<br>// <strong>release(Person(Maxim)), 0 strong references<br></strong>//<strong> person is deinitialized</strong></pre><h3>Autorelease Pool</h3><p>An autorelease pool is an instance of <em>NSAutoreleasePool</em></p><p>It is a mechanism for having deferred <em>release </em>behavior. A pool itself is placed on the stack. It contains the objects, which were added by <em>autorelease </em>method calls. When a pool is being released (removed from the stack), it calls the<em> release</em> method of each item inside (sends a <em>release</em> message to all of them)</p><p>Each function has its pool. When a function is called, a pool is created and put onto the top of the stack. Each object created inside the function, which got an<em> autorelease</em> message, is added to the pool. When the function ends, the pool is being released</p><p>However, if another pool is manually created inside the function, the objects will be added there because now that pool is placed onto the top of the stack. So, objects are added into the last created pool</p><p>In general, there is no need to create pools manually. E.g., UIKit and AppKit create a pool automatically when a touch event starts and release it when the event ends (run loop iteration)</p><p>However, it can be useful to create a pool manually to prevent big memory surges in cycles. E.g., heavy objects that are created on each cycle iteration should be released at the end of the iteration</p><pre>// <strong>some function body</strong></pre><pre>for _ in 0..&lt;10 {<br>    <strong>autoreleasepool</strong> {<br>        // <strong>UIImage inherits NSObject (Objective-C)</strong><br>        let image = UIImage(contentsOfFile: &quot;image.jpg&quot;) // <strong>heavy</strong><br>    }<br>}</pre><p>Let’s imagine that each image takes ~20Mb in memory. So, without <em>autoreleasepool </em>it will take ~200Mb by the end of the function. But now, it takes ~20Mb within the whole function call. Thus, no significant memory surges there</p><p><strong>However,</strong> it works only for Objective-C objects<strong> </strong>(<em>NSObject</em>) that got an<em> autorelease </em>message. For objects that come from Swift, it doesn’t work anyway</p><h3><strong>Strong Reference Cycles Between Class Instances</strong></h3><pre>// <strong>Problem</strong></pre><pre>class Person {<br>    let name: String<br>    init(name: String) { self.name = name }<br>    var apartment: Apartment? // <strong>strong reference<br>    </strong>deinit { print(&quot;person is deinitialized&quot;) }<br>}</pre><pre>// <strong>An</strong> <strong>apartment may not always have a tenant<br></strong>class Apartment {<br>    let unit: String<br>    init(unit: String) { self.unit = unit }<br>    var tenant: Person? // <strong>strong reference</strong><br>    deinit { print(&quot;apartment is deinitialized&quot;) }<br>}</pre><pre>var person: Person?<br>var apartment: Apartment?</pre><pre>person = Person(name: &quot;Maxim&quot;)<br>apartment = Apartment(unit: &quot;1408&quot;)</pre><pre>person!.apartment = apartment // <strong>the</strong> <strong>person refers to the apartment</strong><br>apartment!.person = person    // <strong>the</strong> <strong>apartment refers to the person</strong></pre><pre>person = nil<br>apartment = nil</pre><pre>// <strong>no deinit called<br></strong>// <strong>resources will be never deallocated</strong></pre><p>A<em> weak</em> reference is used when the <strong>object’s lifetime </strong>is<strong> shorter than </strong>its<strong> holder</strong>. It can store <strong>only optional </strong>values. <em>weak</em> tells ARC <strong>not to insert</strong> <em>retain </em>for the object (not to make one more strong reference)</p><p><strong>Note:</strong> Property observers aren’t called when ARC sets a weak reference to <em>nil</em></p><pre>// <strong>Solution (using weak)</strong></pre><pre>class Person {<br>    let name: String<br>    init(name: String) { self.name = name }<br>    var apartment: Apartment? // <strong>strong reference<br>    </strong>deinit { print(&quot;person is deinitialized&quot;) }<br>}</pre><pre>// <strong>An apartment may not always have tenant<br></strong>// <strong>Tenant lifetime is shorter than apartment one <br></strong>class Apartment {<br>    let unit: String<br>    init(unit: String) { self.unit = unit }<strong><br>    weak</strong> var tenant: Person?<br>    deinit { print(&quot;apartment is deinitialized&quot;) }<br>}</pre><pre>var person: Person?<br>var apartment: Apartment?</pre><pre>person = Person(name: &quot;Maxim&quot;)<br>apartment = Apartment(unit: &quot;1408&quot;)</pre><pre>person!.apartment = apartment // <strong>the person refers to apartment</strong><br>apartment!.person = person    // <strong>the apartment refers to person</strong></pre><pre>person = nil<br>apartment = nil<br>// <strong>the person is deinitialized<br>// the apartment is deinitialized</strong></pre><pre><strong>// resources are deallocated</strong></pre><p>An <em>unowned</em> reference is used when the <strong>object’s lifetime</strong> is <strong>the same or longer</strong> than its <strong>holder</strong>. It can store <strong>optional</strong> and <strong>non-optional</strong> values. <em>unowned</em> also tells ARC <strong>not to insert</strong> <em>retain </em>for the object (not to make one more strong reference)</p><p>ARC can make it <em>nil</em>, and if you try to get the value, then you will have the runtime error</p><pre>// <strong>Solution (using unowned)</strong></pre><pre>class Person {<br>    let name: String<br>    init(name: String) { self.name = name }<br>    var card: CreditCard?<br>    deinit { print(&quot;person is deinitialized&quot;) }<br>}</pre><pre>// <strong>A credit card must always have customer<br>// A customer lifetime is the same as credit card one<br></strong>class CreditCard {<br>    let number: Int<br>    <strong>unowned</strong> let customer: Person<br>    init(number: Int, customer: Person) {<br>        self.number = number<br>        self.customer = customer<br>    }<br>    deinit { print(&quot;card is reinitialized&quot;) }<br>}</pre><pre>var person: Person?</pre><pre>person = Person(name: &quot;Maxim&quot;)<br>person!.card = CreditCard(number: 12345, customer: person!)</pre><pre>person = nil<br>// <strong>the person is deinitialized<br></strong>// <strong>the card is deinitialized</strong></pre><pre><strong>// resources are deallocated</strong></pre><p><em>weak</em> and <em>unowned</em> can also be applied to variables</p><pre><strong>weak</strong> var person = Person()<br><strong>unowned</strong> var card = CreditCard()</pre><p>The difference between <em>unowned</em><strong> </strong>and<strong> </strong><em>unowned(unsafe)</em> (<em>unowned</em> is safe by default) is that Swift for <em>unowned</em> checks at runtime whether the object is alive. So, in this case, it works like implicit unwrapping (<em>!</em>). And if the object doesn’t exist (it is <em>nil</em>), Swift throws an error when trying to get the object value</p><p>But when <em>unowned(unsafe)</em> is used, Swift doesn’t verify that the object is still alive, and it can get access to other data stored in this memory region. Thus, in this case, you can get an undefined state. But using <em>unowned(unsafe)</em> can increase performance</p><p><strong>The best practice is </strong>to avoid using <em>unowned</em> at all because the code anyway becomes unsafe. <strong>The best practice is</strong> to use <em>weak</em> always and check explicitly that the object is alive</p><p>ARC is not a garbage collector. Unlike standard garbage collectors, where the resources are deallocated when the app needs memory, objects in Swift are deallocated once the last strong reference gets <em>nil</em> (<em>release </em>calls <em>dealloc</em>)</p><h3><strong>Strong Reference Cycles for Closures</strong></h3><p>A strong reference cycle can also occur if you <strong>assign a closure to a property of a class instance</strong>, and <strong>the body of the closure captures the instance</strong></p><pre>// <strong>Problem</strong></pre><pre>class HTMLElement {<br>    let name: String<br>    let text: String?</pre><pre>    <strong>lazy</strong> var asHTML: <strong>() -&gt; String</strong> = {<br>        if let text = self.text {<br>            return &quot;&lt;\(self.name)&gt;\(text)&lt;/\(self.name)&gt;&quot;<br>        } else {<br>            return &quot;&lt;\(self.name)/&gt;&quot;<br>        }<br>     }</pre><pre>    init(name: String, text: String? = nil) {<br>        self.name = name<br>        self.text = text<br>    }</pre><pre>    deinit {<br>        print(&quot;element is deinitialized&quot;)<br>    }<br>}</pre><pre>var element: HTMLElement? = HTMLElement(<br>    name: &quot;p&quot;, text: &quot;something&quot;<br>)<br>print(element?.asHTML ?? &quot;&quot;)<br>element = nil</pre><pre>// <strong>no deinit called<br></strong>// <strong>resources will be never deallocated</strong></pre><p>There is a capture list that defines the rules to capture objects within the closure body</p><pre>// ... [unowned self, weak delegate = self.delegate, someVariable]</pre><pre>// <strong>Solution</strong></pre><pre>class HTMLElement {<br>    let name: String<br>    let text: String?</pre><pre>    lazy var asHTML: () -&gt; String = { <strong>[weak self]</strong> in<br>        if let text = self?.text {<br>            return &quot;&lt;\(self.name)&gt;\(text)&lt;/\(self.name)&gt;&quot;<br>        } else {<br>            return &quot;&lt;\(self.name)/&gt;&quot;<br>        }<br>     }</pre><pre>     init(name: String, text: String? = nil) {<br>        self.name = name<br>        self.text = text<br>     }</pre><pre>     deinit {<br>        print(&quot;element is deinitialized&quot;)<br>     }<br>}</pre><pre>var element: HTMLElement? = HTMLElement(<br>    name: &quot;p&quot;, text: &quot;something&quot;<br>)<br>print(element?.asHTML ?? &quot;&quot;)<br>element = nil<br>// <strong>the element is deinitialized</strong></pre><pre><strong>// resources are deallocated</strong></pre><h3>Resources</h3><ul><li><a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html">https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html</a></li><li><a href="https://stackoverflow.com/questions/26553924/what-is-the-difference-in-swift-between-unownedsafe-and-unownedunsafe">https://stackoverflow.com/questions/26553924/what-is-the-difference-in-swift-between-unownedsafe-and-unownedunsafe</a></li><li><a href="https://clang.llvm.org/docs/AutomaticReferenceCounting.html">https://clang.llvm.org/docs/AutomaticReferenceCounting.html</a></li><li><a href="https://enterra.ru/blog/garbage_collector_in_ios/">https://enterra.ru/blog/garbage_collector_in_ios/</a></li><li><a href="https://habr.com/ru/post/209288/">https://habr.com/ru/post/209288/</a></li><li><a href="http://macbug.ru/cocoa/memarc">http://macbug.ru/cocoa/memarc</a></li><li><a href="http://macbug.ru/cocoa/mempool">http://macbug.ru/cocoa/mempool</a></li><li><a href="https://proswift.ru/pamyat-i-autoreleasepool-dlya-ciklov/">https://proswift.ru/pamyat-i-autoreleasepool-dlya-ciklov</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a85e56283bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift. Copy-On-Write]]></title>
            <link>https://maxim-kryloff.medium.com/swift-copy-on-write-55b45af7ed7a?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/55b45af7ed7a</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 13:07:04 GMT</pubDate>
            <atom:updated>2021-05-29T16:35:35.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUHaq9PQjoz1xUbI5zPwsA.png" /></figure><p>Here is a quick <a href="https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504">introduction</a>, along with the full articles list</p><p><em>… is all about improving the performance of value types</em></p><p>Copying on write is only about structures that are stored on the heap. It makes real copies of instances <strong>only when </strong>that copies are being changed</p><p>String and all collection types — Array, Dictionary, and Set support this technique (they’re implicitly stored on the heap). But, copy-on-write doesn’t work for all structures by default. When simply copying a structure, it is copied even if its copies are not supposed to be changed. Though the compiler is free to optimize any structure access and effectively give you copy-on-write semantics, this is not guaranteed</p><p>Assignment, initialization, and arguments passing create a new copy of value type data or one more reference to reference type data</p><h3>Array</h3><p>Array filtering makes a <strong>new</strong> array</p><pre>var array = [1, 2, 3, 4, 5]<br>// <strong>0x6000038a0200</strong></pre><pre>var filteredArray = array.filter { $0 &gt; 3 }<br>// <strong>0x6000015b3380</strong></pre><p>Casting to a new type makes a <strong>new</strong> array</p><pre>var array = [1, 2, 3, 4, 5]<br>// <strong>0x6000034393d0</strong></pre><pre>var array2 = array as [Any]<br>// <strong>0x600002234ce0</strong></pre><p>Creating a new array from a given one makes one more <strong>new</strong> array</p><pre>var array = [1, 2, 3, 4, 5]<br>// <strong>0x600001127860</strong></pre><pre>var array2 = Array(arrayLiteral: array)<br>// <strong>0x600003c3f6b0</strong></pre><p>An array supports copy-on-write</p><pre>var array = [1, 2, 3, 4, 5]<br>// <strong>0x600002e30160</strong></pre><pre>var array2 = array<br>// <strong>0x600002e30160</strong></pre><pre>array2.append(6)<br>// <strong>0x600002636320</strong></pre><h3>ArraySlice</h3><p>ArraySlice supports copy-on-write</p><pre>final class Element {<br>    let id: Int<br>    <br>    init(id: Int) {<br>        self.id = id<br>    }<br>    <br>    deinit {<br>        print(&quot;deinit of &#39;\(id)&#39; is called&quot;)<br>    }<br>}</pre><pre>var array: Array&lt;Element&gt;? = [Element(id: 1), Element(id: 2)]<br>// <strong>array is [Element(1), Element(2)]<br></strong>var slice: ArraySlice&lt;Element&gt;? = array!.dropFirst()<br>// <strong>slice is [Element(2)]</strong></pre><pre>slice![slice!.endIndex - 1] = Element(id: 3)<br>// <strong>slice is [Element(3)]<br></strong>//<strong> array is [Element(1), Element(2)]</strong></pre><pre>array = nil<br>// <strong>deinit of &#39;1&#39; is called<br>// deinit of &#39;2&#39; is called</strong></pre><pre>var array2: Array&lt;Element&gt;? = [Element(id: 10), Element(id: 20)]<br>// <strong>array2 is [Element(10), Element(20)]<br></strong>var slice2: ArraySlice&lt;Element&gt;? = array2!.dropFirst()<br>// <strong>slice2 is [Element(20)]</strong></pre><pre>slice2!.append(Element(id: 30))<br>// <strong>slice2 is [Element(20), Element(30)]<br>// array2 is [Element(10), Element(20)]</strong></pre><pre>array2 = nil<br>// <strong>deinit of &#39;10&#39; is called</strong></pre><pre>var array3: Array&lt;Element&gt;? = [Element(id: 100), Element(id: 200)]<br>// <strong>array3 is [Element(100), Element(200)]</strong></pre><pre>var slice3: ArraySlice&lt;Element&gt;? = array3!.dropFirst()<br>// <strong>slice3 is [Element(200)]</strong></pre><pre>array3![array3!.count - 1] = Element(id: 300)<br>// <strong>array3 is [Element(100), Element(300)]<br></strong>//<strong> slice3 is [Element(200)]</strong></pre><pre>array3 = nil<br>// <strong>deinit of &#39;300&#39; is called</strong></pre><pre>var array4: Array&lt;Element&gt;? = [Element(id: 1000), Element(id: 2000)]<br>// <strong>array4 is [Element(1000), Element(2000)]</strong></pre><pre>var slice4: ArraySlice&lt;Element&gt;? = array4!.dropFirst()<br>// <strong>slice4 is [Element(2000)]</strong></pre><pre>array4!.append(Element(id: 3000))<br>// <strong>array4 is [Element(1000), Element(2000), Element(3000)]<br>// slice4 is [Element(2000)]</strong></pre><pre>array4 = nil<br>// <strong>deinit of &#39;3000&#39; is called</strong></pre><p>When a slice is changed, it loses a strong link to the original array’s entire storage. But if the original array is changed, its slices still have a strong link to the old version of the array</p><h3>Set</h3><p>A set supports copy-on-write</p><pre>var set: Set = [1, 2]<br>// <strong>set is [1, 2]</strong></pre><pre>var set2 = set<br>// <strong>set2 is [1, 2]</strong></pre><pre>set2.insert(3)<br>// <strong>set2 is [1, 2, 3], set is [1, 2]</strong></pre><h3>Dictionary</h3><p>A dictionary supports copy-on-write</p><pre>var dictionary = [1: &quot;One&quot;, 2: &quot;Two&quot;, 3: &quot;Three&quot;]<br>var dictionary2 = dictionary<br>dictionary2[1] = &quot;1&quot;</pre><pre>// <strong>dictionary = [3: &quot;Three&quot;, 1: &quot;One&quot;, 2: &quot;Two&quot;]<br></strong>// <strong>dictionary2 = [3&quot; &quot;Three&quot;, 1: &quot;1&quot;, 2: &quot;Two&quot;]</strong></pre><h3>Manual Copy-On-Write</h3><pre>struct User {<br>    var id: Int<br>    var age: Int<br>}</pre><pre>final class ReferenceTo&lt;T&gt; {<br>    var value: T</pre><pre>    init(value: T) {<br>        self.value = value<br>    }<br>}</pre><pre>struct Box&lt;T&gt; {<br>    private var reference: ReferenceTo&lt;T&gt;<br>    <br>    init(value: T) {<br>        reference = ReferenceTo(value: value)<br>    }</pre><pre>    var value: T {<br>        get { return reference.value }<br>        set {<br>            // <strong>returns true if there is only one strong reference<br>            </strong>if isKnownUniquelyReferenced(&amp;reference) {<br>                reference.value = newValue<br>            }<br>            reference = ReferenceTo(value: newValue)<br>        }<br>    }<br>}</pre><pre>var boxedUser = Box&lt;User&gt;(value: User(id: 1, age: 18))<br>// <strong>boxedUser2.value refers to boxedUser.value</strong><br>var boxedUser2 = boxedUser<br>boxedUser2.value.id = 2 // <strong>copying on write</strong><br>// <strong>boxedUser2.value.id is 2, boxedUser.value.id is 1</strong></pre><h3><strong>isKnownUniquelyReferenced</strong></h3><p>The function considers <strong>only strong references</strong>:</p><ul><li>true == strong</li><li>false == strong, strong</li><li>false == weak, unowned</li><li>true == strong, weak, unowned</li></ul><h3>Resources</h3><ul><li><a href="https://www.hackingwithswift.com/example-code/language/what-is-copy-on-write">https://www.hackingwithswift.com/example-code/language/what-is-copy-on-write</a></li><li><a href="https://marcosantadev.com/copy-write-swift-value-types/">https://marcosantadev.com/copy-write-swift-value-types/</a></li><li><a href="https://www.youtube.com/watch?v=66g_pD3s7TY">https://www.youtube.com/watch?v=66g_pD3s7TY</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55b45af7ed7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Swift]]></title>
            <link>https://maxim-kryloff.medium.com/learning-swift-f3a2edce2504?source=rss-12dd38bd5bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3a2edce2504</guid>
            <dc:creator><![CDATA[Maxim Krylov]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 12:02:10 GMT</pubDate>
            <atom:updated>2021-05-29T16:31:38.741Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, everybody! You know, this is the first time when I’m writing an article somewhere. But it is not an article at all. It is something I’m just writing</p><p>My name is Maxim, and I love software development. Currently, I’m learning Swift and iOS. Listening to <a href="https://www.swiftbysundell.com/podcast/">Swift by Sundell</a> podcasts gave me an interesting thought: “If you want to learn something, just write an article about it” Not sure that they said it precisely that way, but it was how I got it</p><p>One more interesting thought is: “If you want to understand something, just teach the computer doing this”</p><p>Do you know what a bicycle looks like? Try to paint it without any picture or looking at a real one. Some people believe that they can easily do this, but when painting, they have troubles</p><p>Or do you know how Message Dispatch works in Swift? Step by Step. From Compilation to Runtime. Say it out loud. Have you managed this?</p><p>Summarizing these thoughts, I would say that if you want to learn something, find a way to check yourself after. Say it to your reflection in the mirror or to your best friend, paint it on A4, or, maybe, write an article!</p><p>When writing these articles, I’m not having a goal of making them beautiful or easy to read for everyone. They are no more than just my notes that contain aggregated and compressed pieces of knowledge. No expressive introductions. No smooth transitions between thoughts. Something comes from Apple docs or other people’s articles. Something comes from people who I spoke with</p><p>Well, that is all I have to say before placing the list of my writings</p><h3>The List</h3><ul><li><a href="https://medium.com/@maxim.kryloff/swift-collections-f8d5a10afb13">Swift. Collections</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-copy-on-write-55b45af7ed7a">Swift. Copy-On-Write</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-arc-7a85e56283bb">Swift. ARC</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-closures-2fcad25790a3">Swift. Closures</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-method-dispatch-4ac7efab0388">Swift. Method Dispatch</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-generics-4faa1cb0b930">Swift. Generics</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-concurrency-810fdbe0b248">Swift. Concurrency</a></li><li><a href="https://medium.com/@maxim.kryloff/swift-static-and-dynamic-libraries-frameworks-343952d3011e">Swift. Static and Dynamic Libraries. Frameworks</a></li><li><a href="https://maxim-kryloff.medium.com/swift-packages-and-bundles-resources-82f06c66b19e">Swift. Packages and Bundles. Resources</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3a2edce2504" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>