<?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 Shripada Hebbar on Medium]]></title>
        <description><![CDATA[Stories by Shripada Hebbar on Medium]]></description>
        <link>https://medium.com/@shripadahebbar?source=rss-35c0321d7ddb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3pavqanGQ2JsL1ol.jpg</url>
            <title>Stories by Shripada Hebbar on Medium</title>
            <link>https://medium.com/@shripadahebbar?source=rss-35c0321d7ddb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:57:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shripadahebbar/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[flatMap in Swift]]></title>
            <link>https://medium.com/@shripadahebbar/flatmap-in-swift-19e6453c9c59?source=rss-35c0321d7ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/19e6453c9c59</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Shripada Hebbar]]></dc:creator>
            <pubDate>Fri, 11 Mar 2016 09:27:20 GMT</pubDate>
            <atom:updated>2018-01-12T12:38:17.145Z</atom:updated>
            <content:encoded><![CDATA[<p>flatMap is yet another higher order function supported by Swift Standard Library. At first glance, this function looks a bit allusive to understand. There are many flavours of this. We will examine most used 3 flavours here.</p><h4><strong>Flavour-1</strong>: With Optionals</h4><p>Yes, you can flatMap on Optionals. See the declaration of enum Optional:</p><pre>public enum Optional&lt;Wrapped&gt; : _Reflectable, NilLiteralConvertible {<br>...<br> /// Returns `nil` if `self` is nil, `f(self!)` otherwise.<br> @warn_unused_result<br>public func flatMap&lt;U&gt;(@noescape f: (Wrapped) throws -&gt; U?) rethrows -&gt;   U?<br>...<br>}</pre><p>Read the comments- <strong>This Returns ‘nil’ if ‘self’ is nil, ‘f(self!)’ otherwise. </strong>So the result of a <strong>flatMap</strong> on an optional is always an optional. <strong>flatMap</strong> will <strong>safely</strong> unwrap the self and call your transform function. If self is <em>nil</em>, it will simply return <em>nil</em> as return value and transform will never get called.</p><p>Interesting isn&#39;t it? 😀 Where this could be useful?. Let us consider few uses:</p><ul><li>Creating image from a CGImage created from a bitmap context.</li></ul><pre>let scaledImage = CGBitmapContextCreateImage(context).flatMap { UIImage(CGImage: $<strong>0</strong>) } </pre><p>Here the CGImage that gets created using CGBitmapContextCreateImage might fail, and hence it could be nil. So this is an optional CGImage object. We are using flatMap on it to create UIImage. If it is non nil, we get an optional UIImage, otherwise nil. If it were not the flatMap, the code would have been bit lengthier-</p><pre>if let cgImage = CGBitmapContextCreateImage(context){<br>scaledImage = cgImage<br>}else{<br>scaledImage = nil<br>}</pre><ul><li>Creating NSData from a NSURL.</li></ul><pre>let data = NSURL(string : filePath).flatMap{NSData(contentsOfURL: $0)}</pre><p>If it were not the flatMap, the same would have been more code:</p><pre>if let url = NSURL(string : filePath),<br>let data = NSData(contentsOfURL: url){<br>  //Do something with data<br>}</pre><h4>Flavour 2: With Arrays — apply transform and flatten</h4><p>Let us take a look at the following declaration of the extension on SequenceType:</p><pre>extension SequenceType {</pre><pre>/// Return an `Array` containing the concatenated results of mapping<br>/// `transform` over `self`.<br>///<br>/// s.flatMap(transform)<br>///<br>/// is equivalent to<br>///<br>/// Array(s.map(transform).flatten())<br>///<br>/// — Complexity: O(*M* + *N*), where *M* is the length of `self`<br>/// and *N* is the length of the result.<br>@warn_unused_result<br>public func flatMap&lt;S : SequenceType&gt;(transform: (Self.Generator.Element) throws -&gt; S) rethrows -&gt; [S.Generator.Element]<br>}</pre><p>Observe that the transform function that the flatMap expects always processes an element of the Self and generates a SequenceType being desired. Once each Element of the Self is processed using the transform, flatMap will create another SequenceType and put Elements of each of the SequenceType produced by the transform. This whole thing is captured in the comment-</p><pre>// s.flatMap(transform)<br>///<br>/// is equivalent to<br>///<br>/// Array(s.map(transform).flatten())<br></pre><p>Confused? Don&#39;t worry, let us take an example. Suppose that we want to generate sqaures and cubes of first 3 natural numbers and flatten them into a sequence. [We want to use this to pose a challenge to a user to guess the next number in the series 😀]</p><pre>let numbers = [1,2,3]<br>let squaresAndCubes = numbers.map{ [$0*$0, $0 * $0 * $0]}<br>print(squaresAndCubes)//[[1,1],[4,8],[9,27]]<br>let flattened = squaresAndCubes.flatten()//Flatten simply concatenates the elements of the sequence<br>print(flattened)//[1,1,4,8,9,27]</pre><p><strong><em>flatMap</em></strong> will help us to do the map and flatten in one go-</p><pre>let flattned =  numbers.flatMap{[$0*$0, $0*$0*$0]}</pre><h4>Flavour 3 : With Arrays, if transform produces nil, it will be ignored from the resultant sequence.</h4><p>Check this extension-</p><pre>extension SequenceType {<br>/// Return an `Array` containing the non-nil results of mapping<br>/// `transform` over `self`.<br>///<br>/// — Complexity: O(*M* + *N*), where *M* is the length of `self`<br>/// and *N* is the length of the result.<br>@warn_unused_result<br>public func flatMap&lt;T&gt;(@noescape transform: (Self.Generator.Element) throws -&gt; T?) rethrows -&gt; [T]<br>}</pre><p>A good example would be to create UIImage files from an array of image names. If for any name, image creation returns nil, it will be simply ignored in the resultant array of UIImage objects.</p><pre>let imageNames = [“top”, “left”, “right”, “bottom”, “nonexistent”]</pre><pre>let images = imageNames.flatMap{ UIImage(name: $0)} //[UIImage] sans the //image for icon with name &quot;nonexistent&quot;</pre><p>We can even use flatMap to filter out any nil objects present in an array of optionals and also unwrap non nil items all in one go. Check the following example-</p><pre>let optionals : [Int?] = [2, 4, nil, 6, 8, nil, 10]</pre><pre>let nonNilInts = optionals.flatMap{$0} //[2,4,6,8,10] and type is [Int]</pre><p>Hope now flatMap is clearer and is no more allusive to understand! 😀</p><p>I invite you to read more on flatMap by various talented developers in the following links-</p><ul><li><a href="http://alisoftware.github.io/swift/2015/10/11/thinking-in-swift-4/">Thinking in Swift, Part 4: map all the things!</a></li><li><a href="https://www.natashatherobot.com/swift-2-flatmap/">Swift 2.0: Understanding flatMap</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19e6453c9c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Programming Language]]></title>
            <link>https://medium.com/@shripadahebbar/swift-programming-language-cfe38ef32b1e?source=rss-35c0321d7ddb------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfe38ef32b1e</guid>
            <dc:creator><![CDATA[Shripada Hebbar]]></dc:creator>
            <pubDate>Wed, 05 Nov 2014 10:17:15 GMT</pubDate>
            <atom:updated>2014-11-05T10:17:15.773Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift learning — day 1</h3><p>Today, I started reading Apple’s The Swift Programming Language documentation. I personally recommend reading Apple’s docs before you ever read so called tutorials and other related materials.</p><p>I sensed a considerable cognitive load w.r.t the syntax, having programmed in C/C++/Objective C for so many years. But trust me, that is way easier to grasp as you turn the pages.</p><p>var — introduces a variable</p><p>let — introduces a constant. A constant in swift is way much more than the constant in C. But seems we will come across this later</p><p>so if something does not change it must be declared and defined using let.</p><blockquote>let maximumHeight = 100.0</blockquote><p>The above line introduces a constant which is denoting value 100 and can never change.</p><blockquote>var x = 0</blockquote><blockquote>x * = 2</blockquote><p>Though swift provides type inferencing, we might want to decorate the variable declarations with exact types for better readability and help compiler.</p><blockquote>var x : double</blockquote><blockquote>x = 100</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfe38ef32b1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>