<?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 Sergey Smagleev on Medium]]></title>
        <description><![CDATA[Stories by Sergey Smagleev on Medium]]></description>
        <link>https://medium.com/@sergeysmagleev?source=rss-8a5158ab170d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s6ryu0Yso7rU1R3FqizH_A.jpeg</url>
            <title>Stories by Sergey Smagleev on Medium</title>
            <link>https://medium.com/@sergeysmagleev?source=rss-8a5158ab170d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:17:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergeysmagleev/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[How to implement your own Optional Chaining in Swift]]></title>
            <link>https://medium.com/@sergeysmagleev/how-to-implement-your-own-optional-chaining-in-swift-6cf32e902c3c?source=rss-8a5158ab170d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf32e902c3c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sergey Smagleev]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 10:22:42 GMT</pubDate>
            <atom:updated>2019-03-19T10:22:42.342Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deeper look at .map and .flatMap operators</h4><p>Ever since I started programming in Swift I couldn’t help but use functions like map, reduce, filter etc. when performing all sorts of operations on arrays. There’s something so enjoyable about them that I’ll never miss a chance to turn my usual array processing routine into a chain of these nifty functional operators. But what if I told you that you can extend the usage of this concept beyond just collection types?</p><p>It might not be big news for you, but you can use map operator with an Optional type.</p><p>Nothing illustrates a coding problem better than a good old “Hello world”. Here’s a function that takes a string and prefixes it with “Hello”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8c434a9337abc85acebc9bd3f25617/href">https://medium.com/media/8e8c434a9337abc85acebc9bd3f25617/href</a></iframe><p>But what happens if we want to make both input and output Optionals? It will give us few extra steps with the need to filter out the nil’s:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8941fda45a03b90b304ffa1c17531fdb/href">https://medium.com/media/8941fda45a03b90b304ffa1c17531fdb/href</a></iframe><p>The guard let statement is the usual way to unwrap optionals, but notice how the function has become so much longer just because we decided to support them. Is there an easier way to write it? Yes, there is. Take a look at this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d38945cb0b6f80a9925295c28d0d496/href">https://medium.com/media/5d38945cb0b6f80a9925295c28d0d496/href</a></iframe><p>These two functions are equivalent, but the second one looks more concise and similar to the original and we’ve achieved this using only one operator.</p><p>The operator we’re using is called map, just like Array&lt;T&gt;.map. Despite the fact these two data types are fundamentally different, - one being an enum and another one being a collection type, - the map operators they both have are actually following the same logic.</p><p>Both Array&lt;T&gt; and Optional&lt;T&gt; are generic constructs that contain an internal type. For each type like this map is an operator that transforms a <em>wrapped</em> value T stored inside a <em>wrapping</em> object of type Type&lt;T&gt; into a value of type U and produces a <em>wrapping</em> object of type Type&lt;U&gt; with the transformed value inside. Here’s how the signature of this operator looks:</p><p>map&lt;U&gt;(f: (T) -&gt; U) -&gt; Type&lt;U&gt;</p><p>In other words, it transforms the value inside the wrapper object and leaves it wrapped in there. It makes sense for both optionals and arrays. We may want to transform an optional value into something else and leave it optional, as well as we might want to transform one array into another without having to loop over each item individually and placing them in a new array.</p><p>That’s the main purpose of map operator in functional programming. It performs wrapping and unwrapping for you so that you don’t have to bother about boilerplate code while focusing on the actual values, allowing for a more “declarative” way of defining the logic.</p><p>Let’s get back to the previous example. It may so happen that one of the intermediate results of the mapping chain will also return an optional object. Let’s create a function named helloRoot that calculates the square root of a Double and prints out the string “Square root equals \(value)”, but instead of using the built-in method sqrt directly let’s wrap it into a function that returns nil for negative input so that we don’t end up with a nan:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16fba8bed3a0dead346d48aa629cc174/href">https://medium.com/media/16fba8bed3a0dead346d48aa629cc174/href</a></iframe><p>And then the actual function helloRoot looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41b797d3ef6ede2469c18b5f0b8d660f/href">https://medium.com/media/41b797d3ef6ede2469c18b5f0b8d660f/href</a></iframe><p>This stack of map operators look very aesthetically clean. It’s easy to read and see what happens at each line. Unfortunately, the final result doesn’t look so nice. For example, if we pass 25 as an input it will return “Square root equals Optional(5.0)”, and if we pass a negative parameter it will print “Square root equals nil”. Technically correct, but not visually pleasing. If only there was a way to remove the garbage from the output and not print anything at all if there’s nothing to print.</p><p>We’ve run into an issue where one of the map operators gives us Optional&lt;Optional&lt;Double&gt;&gt;. This should come as no surprise since root method returns Double?.</p><p>Before finding a way to fix it, let’s take a look at the trivial solution with guard/else statement that unwraps the values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1f5786a20e8387a6a3b54625aecdf74/href">https://medium.com/media/e1f5786a20e8387a6a3b54625aecdf74/href</a></iframe><p>This code does the job correctly and some may argue that this is a more correct way to <em>handle</em> the result. This syntax isn’t hard to follow either, but somehow it’s a bit clunky in our example. Aside from losing the charm of declarative syntax, my main concern is that we “break” the current context by doing the unwrapping. See, both input and output values are optional, so what we’re dealing with here is we <em>unwrap</em> the input variable in order to then <em>wrap it back</em> right after.</p><p>Luckily there’s a way to get rid of the nesting that map operators produce. If you’re experienced with mapping functions of Array type, you may already see that I’m talking about flatMap. It works similarly to map, except it expects the transforming function to return the value of its own type Type&lt;U&gt;, but unlike map it won’t rewrap it into another layer of Type&lt;Type&lt;U&gt;&gt; but leave it as is. Hence, it’s sort of “flattening down” the nested values. Here’s its signature:</p><p>flatMap&lt;U&gt;(f: (T) -&gt; Type&lt;U&gt;) -&gt; Type&lt;U&gt;</p><p>Now let’s jump back to helloRoot with two mapping functions and do this little change on line 3:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d683d74380e15cab414e5d44643514b/href">https://medium.com/media/2d683d74380e15cab414e5d44643514b/href</a></iframe><p>Voila! We got rid of the garbage in the output. If we pass 25 as an input it will print “Square root equals 5.0”, and if we pass a faulty input it will return nil.</p><p>Here’s a quick cheat-sheet about how each of the discussed operators work with various transformations functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dm_sN3X1-BafYhWzvWy6A.png" /></figure><ol><li>map is used to convert the value of an optional into another value, presumably also of different type. If there’s a value inside the optional then it will go through the entire chain of transformations. If not, it will keep returning nil. Simple.</li><li>map is used to convert the value of an optional into another optional. The behavior for nil won’t change, but for a non-nil value every other transform will add one more layer of nesting, e.g. you’ll go from .some(T) to .some(.some(U)), then .some(.some(.some(V))) etc.</li><li>flatMap is used to convert a value into another optional, just like in the previous example. However, each new layer is “flattened” to the current level, so in the end only one Optional object remains. Similarly to a bowling ball that falls off the lane and keeps rolling down the gutter, once the value turns nil all subsequent transformations are ignored and it remains nil until the end of the chain.</li></ol><p>Hopefully, this gives you a better understanding of how these functions behave and which advantages they bring you. You may also notice that this concept is implemented quite often for various data types. For instance, a very popularResult&lt;T, Error&gt; type that’s widely used as a container for both values and errors coming from network requests. Many implementations, like <a href="https://github.com/antitypical/Result#higher-order-functions">this one</a> for example, also support map and flatMap functionality.</p><p>But wait, there’s more. Take a look at the picture again, specifically the flatMap part. Does this behavior remind you of something? The execution goes down the chain of optional values until it either finishes successfully or hits a nil. If you think about it, <a href="https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html">Optional Chaining</a> works the exact same way. So, there has to be a way to come up with our own implementation of Optional Chaining using only map and flatMap operators.</p><p>Assume that instead of applying transformation functions we’d like to access certain properties. Starting with Swift version 4, we can use KeyPath syntax to access properties by passing their name as a function parameter. Then we’ll use flatMap to read optional properties and map to access non-optional ones. In order to mimic the original syntax we will write an extension and use some operator you like the most, i.e. ~&gt;. The extension looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6da9e558fabdfc733d60fbfd6d797e02/href">https://medium.com/media/6da9e558fabdfc733d60fbfd6d797e02/href</a></iframe><p>With the power of method overriding we can use the same method signature when handling both normal and optional variables, which will result in a homogenous syntax so that whoever uses these operators won’t have to know about which method lies underneath.</p><p>Give it a try! This new operator can be used as an alternative to the built-in chaining syntax. Like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b86c0b5b0696e312150058e92cf953f2/href">https://medium.com/media/b86c0b5b0696e312150058e92cf953f2/href</a></iframe><p>There’s virtually no difference, you can use them interchangeably!</p><p>As you can see, Optional Chaining is no magic and merely is a syntactic sugar over a mechanism that you can implement on your own using the power of higher order functions. Now you know how to use map and flatMap to your advantage to write more declarative code and you’re ready to tackle functional paradigms like RxSwift.</p><p>Don’t forget that Swift is open-source! If you’d like to learn more, you can study <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/Optional.swift">the source code</a> of Optional type yourself.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf32e902c3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How “defer” operator in Swift actually works]]></title>
            <link>https://medium.com/@sergeysmagleev/how-defer-operator-in-swift-actually-works-30dbacb3477b?source=rss-8a5158ab170d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dbacb3477b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sergey Smagleev]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 00:37:52 GMT</pubDate>
            <atom:updated>2019-02-11T10:42:38.671Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduced in Swift 2, defer isn’t one of the massively used operators in Swift, so chances are you might not even know what it’s meant to do. defer is an operator that’s used with a closure where you include a piece of code that is supposed to be executed at the very end of the current scope. It’s useful if you’ve got many return statements in a method and don’t want to copy and paste the same code before each of them. The code that you’d put into defer is usually a cleanup routine that accompanies commands that allocate or capture resources when the function starts. For example, if you’re implementing thread-safe behavior and locking an NSLock object before running the logic inside the function, putting a defer { lock.unlock() } together with it guarantees that it won’t cause a deadlock or a memory leak.</p><p>However, there’s an extra convenience it comes with which is not so apparent from the description. We know that it’s executed at the end of a function, but where exactly? Let’s take a closer look.</p><h3>Example #1</h3><p>Let’s take a look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/959cbce8c24adc287123f262b2095e20/href">https://medium.com/media/959cbce8c24adc287123f262b2095e20/href</a></iframe><p>Pretty simple indeed and the defer statement even seems redundant here. Since the only other line in this function is return a we may assume that it can be simplified to look like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71eb53e6ba04e746ae0f8f12d0e565a2/href">https://medium.com/media/71eb53e6ba04e746ae0f8f12d0e565a2/href</a></iframe><p>Is b() fully equivalent to d()? Let’s see what they return given the same initial input:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc24e7441032cc38bfd93258a3584423/href">https://medium.com/media/dc24e7441032cc38bfd93258a3584423/href</a></iframe><p>And here’s what’s printed out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c19d00a428f54ff7bb88cdc5a3886752/href">https://medium.com/media/c19d00a428f54ff7bb88cdc5a3886752/href</a></iframe><p>You probably saw it coming. It appears that wrapping a statement inside a defer statement causes it to be, well, deferred past the moment the function returns a value. The output proves this idea but there are a couple of inconsistencies. First of all, it contradicts the definition, which states:</p><blockquote>A <em>defer</em> statement is used for executing code <strong>just before</strong> transferring program control outside of the scope that the <em>defer</em> statement appears in.</blockquote><p>But more importantly, it’s simply technically impossible to perform any task after the function has returned. See, any function in practically any programming language ultimately finishes with a return statement. Once it hits return the execution leaves the current scope, disposes all the local resources, pops the function from the stack and jumps to where it left off one step up the call hierarchy.</p><p>You might get confused into thinking that it‘s doable because you remember using autorelease in Objective-C which allowed for freeing up resources after returning them in a method. Unfortunately, that’s a whole different story. The way it works is that there’s an autorelease pool which drains at every iteration of the current Run Loop which sends a release message to each object marked as autoreleased within the current scope. But defer doesn’t have these tricks up its sleeves.</p><p>To find out what’s actually going on let’s put it through <a href="https://www.hopperapp.com/">Hopper Disassembler </a>and check the results. Compile the code you’ve written with the following command:</p><p>xcrun swiftc your_source_code.swift -o output_file</p><p>Then, download Hopper, run it and load output_file in there. Hopper will break down the whole app into the list of executable processor instructions. Also, for the sake of readability, it will generate a C-like pseudocode out of it. That’s exactly what we need. Here’s what a disassembled pseudocode of function b() looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ff8d58f1e7c3c8a75c766f0de72743/href">https://medium.com/media/92ff8d58f1e7c3c8a75c766f0de72743/href</a></iframe><p>It takes a while to process what’s going on here, so take your time. First things first, the first function up there represents b(), and the second one is the closure that you pass to the defer operator. Notice that return statements are, as expected, the last operations of both methods. Calls to swift_beginAccess and swift_endAccess are the result of accessing the global variable a. You don’t need to focus on all of the random variables being passed around in there, it’s not that relevant.</p><p>The key lines are 3, 6, and 7. At line 3 the initial value of a is stored in rcx register. Then, whatever you pass to defer is called at line 6. In our case, defer generates a new string “ world” and concatenates it with the string a. Ignore the fact that defer puts something into rax and returns it. It’s just a convention that the returned value is stored in this register. Now moving back to the first function. As soon as we’re done with defer the previously saved value is moved back from rcx to rax at line 7 and is returned at the next step.</p><p>Long story short, the trick was to save the original value before calling defer and applying the side effect. Therefore, the real equivalent of function b() without defer would involve a temporary variable to store the contents of a before modifying it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16bddb6849f4a2dc3a5fcbd91c8b3cd1/href">https://medium.com/media/16bddb6849f4a2dc3a5fcbd91c8b3cd1/href</a></iframe><p>Not much of a difference. However, it seemingly creates a bit of complexity by introducing one extra variable, so you might be wondering if it also creates any memory overhead. Does it? To dig deeper into this issue we first need to address the topic of how variables behave at assignment operation.</p><p>There are two types of data in Swift: those that are passed by value (structs and primitives) and those that are passed by reference (classes). If you try to pull this off with a reference type object then it just won’t work the same way. No matter how you do it, if you modify it inside the function it will return the latest edit.</p><p>But String is a value type, meaning that each assignment will spawn a new copy of it. But of course, it’s not that simple. String itself is just a wrapper of constant size of 16 bytes no matter how huge your wall of text is. The underlying character buffer which contains the actual text, however, is a reference type, and it retains the copy-on-write semantics to save memory footprint during assigning operations. Check out <a href="https://developer.apple.com/videos/play/wwdc2015/414/">this WWDC video</a> to learn more about copy-on-write. So, regardless of how many String variables you declare that read the value from a, the actual copying only happens once when a.append(“ world”) is called.</p><p>So in theory there is no significant burden caused by an extra variable, thanks to the copy-on-write semantics that String implements. However, if you copy/paste the contents of disassembled defer into disassembled b() you’ll notice that the internals of b() and c() are nearly identical:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10662ee68a0ff7947b7baf7b7b3e6dfb/href">https://medium.com/media/10662ee68a0ff7947b7baf7b7b3e6dfb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d254b77d84953827e5e9022b4125164c/href">https://medium.com/media/d254b77d84953827e5e9022b4125164c/href</a></iframe><h3>Example #2</h3><p>Moving on, let’s examine another fragment of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2857ad0f8efa3050e4f9697719f0f5/href">https://medium.com/media/3d2857ad0f8efa3050e4f9697719f0f5/href</a></iframe><p>This one is more interesting. In a way, it resembles a common use case of defer which is disposing a captured resource before leaving the current scope. In our example it’s simplified as a global Optional &lt;String&gt; which is assigned a value at the beginning of a function and then turns into nil at the end of it.</p><p>This function will successfully print out “Hello world”. It sure does make sense, but hold on. Didn’t we just prove that a = nil inevitably occurs inside the function? So then, how come it doesn’t crash at force unwrapping?</p><p>Without further ado, let’s take a look at what this function looks like when put through Hopper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab10674a77cd011a2ed1e126c9cc0856/href">https://medium.com/media/ab10674a77cd011a2ed1e126c9cc0856/href</a></iframe><p>Whoa, a simple three-liner has turned into this abomination that spans 34 lines of code. Don’t bother figuring out every single line in this pile of characters and digits, we’ll just need to group it into meaningful chunks to analyze the algorithm. Lines 2 to 9, for example, represent the first line in the original function b() where we assign “Hello world” string to variable a. The call to defer is that mere line number 20, which means that everything else in here belongs to the seemingly trivial operation return a!.</p><p>In fact, return a! isn’t as simple as it looks. Behind the scenes there are three operations going on:</p><ol><li>Reading the value of a and saving it in the local scope. This happens between the second pair of swift_beginAccess/swift_endAccess at lines 10 and 16.</li><li>Unwrapping the value we received on the previous step. This, as you’ve probably guessed already, is what the if statement between the lines 17 and 32 is for. Lines 18 to 21 signify a successful outcome when the value exists, and lines 24 to 31 engage the crash routine which happens when you pass a nil for unwrapping.</li><li>Finally, the actual return! It’s at line 33, you can’t miss it.</li></ol><p>In case that was tough to process, I made a color-coded version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLm_mYAaMYEtrb4VuR79Lw.png" /></figure><p>And here’s what these lines represent in the original function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*N1OCRNCmXQTrggDFPLHrLg.png" /></figure><p>Paying close attention to where defer can be found in the disassembled code answers many questions. For example, now it’s clear that the app doesn’t crash because the assignment a = nil (red) happens after the last time the value of a has been read (blue). But meanwhile there’s something more fascinating. See how defer appears not before, not after, but in the middle of the force unwrapping routine. It’s quite fascinating that you can find the deferred code injected into the implementation of another method. One can argue though that the compiler doesn’t have to perform any complex calculations. All it does it put the call to defer right before the function finishes. And yet, the fact that it can traverse so deep is impressive.</p><h3>The Conclusions!</h3><p>For such a simple operator, defer is doing a really good job of pushing itself to its limits. The true power of this method is that it can “split” the conventional Swift return statement into individual low level operations and squeeze itself in between right before the very last returning processor instruction (aka ret). This way, it makes for more elegant and natural code without the necessity of adding “temporary” intermediate variables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dbacb3477b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>