<?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 Muhammad Hassan on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Hassan on Medium]]></description>
        <link>https://medium.com/@hassankhll?source=rss-c08f5f0a9a43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CrsftsMs_eqcaGpUb3J5yA@2x.jpeg</url>
            <title>Stories by Muhammad Hassan on Medium</title>
            <link>https://medium.com/@hassankhll?source=rss-c08f5f0a9a43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:41:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hassankhll/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[Everything about Swift optionals]]></title>
            <link>https://medium.com/@hassankhll/everything-about-swift-optionals-93e6a2d30d94?source=rss-c08f5f0a9a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e6a2d30d94</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Muhammad Hassan]]></dc:creator>
            <pubDate>Wed, 08 Aug 2018 11:51:54 GMT</pubDate>
            <atom:updated>2018-08-08T11:51:54.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBI0f33phFekuPtvJHwCKw.png" /></figure><p>Swift brought a lot of new features that weren’t part of Objective-C. One of those features is <strong>Optionals</strong>. While Objective-C provided a way to mark variables nullable, Swift has implemented optionals at whole new level . Before we dive into details, let’s first discuss why do we need them in first place. Data is a crucial part of any software. In real world, data availability isn’t always guaranteed. For example, a call to an API might fail due to some network issue. Being a developer, it’s up to you to handle such cases in a friendly way. In other words, at times, we have cases when we might have valid data or might not. And that’s the core idea behind optionals. Let’s discuss it in details.</p><h3>Introduction</h3><p>In Swift, optionals let us handle cases where we might have a legitimate value or we might not. At first, this seems obvious because in many other languages, we get this behavior with regular data holders. For example in Java:</p><pre>String message = &quot;Hello, World!&quot;;<br>System.out.print(str); // &quot;Hello, World!&quot;<br><br>// Can assign null/nil to regular string holder<br>message = null;<br>System.out.print(message); // null</pre><p>In Swift, it’s very different. A regular Swift variable can’t be assigned nil. Therefore, to express absence of a value, you need to use optionals. In fact, it is the only thing you can assign nil to in Swift. To declare a data member as optional, you need to add ? right after the data type.</p><pre>var id: Int<br>id = nil // compile error</pre><pre>var optionalId: Int? // Optional Int<br>optionalID = nil // legitimate Swift expression</pre><p>And it makes sense because if there’s even a slight possibility for a piece of data to be missing, you need to express it right there. A common mistake many developers commit from time to time is to access a variable in a vulnerable way which doesn’t hold any legitimate value and end up having a runtime crash. With optionals, it’s taken care of at compile time. Think of an optional as a strongly typed container which either contains a value or nil otherwise. If it contains a value, you can unwrap the container and use the underlying value. For this, you use an extra bit of information which determines how the underlying value is unwrapped. Let’s take a detailed look into each.</p><h3>Forced Unwrapping!</h3><p>As the term says, you forcefully unwrap the container and try to get the actual value. You get the value if there’s one or the runtime crash otherwise. Safe side is to use this approach when you’re <strong>one hundred percent sure</strong> about the existence of underlying value. For example, if an optional is declared and immediately given an initial value, now it is safe to force unwrap it. Additionally, you can check whether an optional contains a value by checking it against nil. e.g.</p><pre>// Optional Int<br>var randomNumber: Int?</pre><pre>randomNumber = Int(arc4random_uniform(10))</pre><pre>// Forced unwrapping<br>print(randomNumber!)</pre><pre>// Safety check<br>if randomNumber != nil {<br>    print(randomNumber!)<br>}</pre><p>However, it is still the least favourite way to work with optionals in community. In fact, it is considered as one of the reason to introduce <a href="https://en.wikipedia.org/wiki/Code_smell">code smell</a> into codebase. There’s a better approach to unwrap optionals: Optional Binding.</p><h3>Optional Binding</h3><p>In this approach, we create a temporary constant which is only accessible within the braces of if statement. Here, we hit two birds with one stone. First, an optional is checked whether it’s nil. If it’s not nil, it is unwrapped and the constant is assigned this value. Inside curly braces, we can use this constant just like a regular piece of data.</p><pre>let myOptional: Double? = 16</pre><pre>if let temperature = myOptional {<br>    // temperature is of type Double, not Optional Double<br>    print(temperature) // 16<br>}<br>// temperature doesn&#39;t exist here</pre><p>Now, a significant plus of this approach is, you’re not forcefully unwrapping your optional. <em>“But we can use if statement to check an optional against nil” </em>you may ask. Yes, you can. But, still it’s a forced unwrapping. Consider a race condition where nil check is passed but before forced unwrapping, another part of your application assigned nil to your optional. In optional binding, you check and unwrap safely in a single statement.</p><h3>Behind the Scene</h3><p>Using question mark to make an optional is basically a syntactic sugar. Behind the scene, we’ve another language feature powering optionals. If we take a closer look, an optional deals in 2 cases, value, or no value. Speaking of cases, it makes a good candidate for an Enum. And that’s exactly the way Optionals are implemented in Swift. At its core, optional definition looks like this:</p><pre>enum Optional&lt;T&gt; {<br>    case none<br>    case some(T)<br>}</pre><p>Which means:</p><pre>// when you&#39;re saying<br>let quote: String? = nil</pre><pre>// What you’re really saying is<br>let quote = Optional&lt;String&gt;.none</pre><pre>// Similarly<br>let quote: String? = “Hello, World!”</pre><pre>// is equivalent to <br>let quote = Optional&lt;String&gt;.some(“Hello, World!&quot;)</pre><p>Here T represents generic type hence you can create an optional of any type.</p><h3>Optional Chaining</h3><p>Objects can have nested objects. When you try to access one of the nested object while the container object is an optional, you need to define how do you want to unwrap it first to access nested object. We’ve seen optional binding as one of the approach to unwrap an optional. But when it comes to query properties or call methods on an optional, it’s tedious to optional bind every time. All you want is if the optional isn’t nil, call some method on it or query a certain property and that’s what optional chaining provides you with. All you need is to add question mark before dot when querying a property or calling a method. This way, if the optional is nil, that statement fails without crashing your app. Else, your statement works successfully.</p><pre>struct Person {<br>    var name: String<br>    var car: Car?<br>}</pre><pre>struct Car {<br>    var seatingCapacity: Int<br>}</pre><pre>let john = Person(&quot;John&quot;)<br>let seatingCapacity = john.car?.capacity   // seatingCapacity is nil</pre><h3>Explicitly Unwrapped Optional!</h3><p>So far optionals seem an elegant way to deal with an absence of value and that’s true. But at times, having to unwrap an optional every time becomes tedious when you know it’s not nil. A very common scenario is your outlets. When a ViewController gets initialized while your scene in storyboard is not hooked yet, these outlets are nil. So you can’t define them as non-optional variables as Swift enforces data members to always have a legitimate value. However, as soon as your scene is hooked with ViewController, every outlet is set and you can safely assume them to have a value all the time. And Swift does provide you with that option, named as “Implicitly Unwrapped Optionals”. To define one, place an exclamation mark after the type. e.g.</p><pre>let backgroundView: UIView!<br>backgroundView.backgroundColor = UIColor.blue</pre><p>Notice that I didn’t use optional chaining here to access backgroundColor. I didn’t need to; hence the name <em>implicitly unwrapped optional</em>. Although it’s a convenience, it should be used <strong>carefully</strong>. Accessing an implicitly unwrapped optional which doesn’t hold a value would end up in a runtime crash. They’re handy when a variable is accessed <strong>after</strong> assigned a value and guaranteed to hold this value for the lifetime of container object. IBOutlets are typical example that make a good candidate for implicitly unwrapped optionals.</p><pre>Therefore, instead of doing<br><a href="http://twitter.com/IBOutlet">@IBOutlet</a> var nameLabel: UILabel?</pre><pre>We do<br><a href="http://twitter.com/IBOutlet">@IBOutlet</a> var nameLabel: UILabel!</pre><h3>Early Exit</h3><p>At times, absence of value means exit a block of code immediately. Consider an example of making an expensive network request based on a required parameter which is an optional. It would be a wasted server hit if nil is passed as parameter. Combined with guard statement, we can do this:</p><pre>guard let seachInput = searchTextField.text {<br>     // perform operation<br>} else {<br>    // early exit<br>    return<br>}</pre><h3>Failable Initializers</h3><p>In some cases, instantiation of a class or struct can fail. For example:</p><pre>let number = Int(&quot;Hello, World!&quot;)</pre><p>Here, we’re trying to initialize an Int from a string literal that isn’t an integer. In such cases, instantiation fails and nil is returned instead. For example:</p><pre>struct Person {<br>    init?(_ dictionary: [String: Any]) {<br>         guard let name = dictionary[&quot;name&quot;] as? String else {   return nil }<br>          self.name = name<br>}</pre><p>Notice init?. That’s what makes an initializer <em>failable</em>. It’s mandatory for failable initializers to return nil if initialization fails and for that reason instance created from failable initializer is always an <strong>optional</strong>.</p><h3>Nil-Coalescing Operator</h3><p>Consider the following case:</p><pre>let displayingImage = UIImage!</pre><pre>if let profileImage = UIImage(named: &quot;profileImage&quot;) {<br>    displayingImage = profileImage<br>} else {<br>    displayingImage = placeholderImage<br>}</pre><p>Essentially, what I’m doing here is providing a fallback or <strong>default value</strong> in case primary value was missing. That’s what nil-coalescing operator does. E.g.</p><pre>let displayingImage = UIImage(named &quot;profileImage&quot;) ?? placeholderImage</pre><p>It’s a handy way to provide default value in case an optional is nil. Note that nil-coalescing operating doesn’t guarantee to provide a legitimate value. If default value also happens to be an optional, final evaluated value would be an optional as well.</p><h3>Role in Error Handling</h3><p>While this post is not about error handling, I will discuss the part optionals play in handling errors which is significant. In Swift, try comes in three variants: try, try?, try!</p><p>Plain try has two use cases. First, you take the responsibility to handle errors and provide catch block. E.g.</p><pre>do {<br>    let json = try JSONSerialization.jsonObject(with: data, options: [])<br>} catch {<br>    print(error.localizedDescription)<br>}</pre><p>Second case is to pass the error to the next caller in call chain e.g.</p><pre>func parseJson() throws {<br>    let json = try JSONSerialization.jsonObject(with: data, options: [])<br>}</pre><p>Now comes the optionals’ part. try! and try?. You use either one without using do-catch block. As you might have guessed, try! will execute given statement and if an error is thrown, your program terminates immediately.</p><pre>let json = try! JSONSerialization.jsonObject(with: data, options: [])</pre><p>Conversely, try? gives you safe hand but provides you with an optional.</p><pre>let json = try? JSONSerialization.jsonObject(with: data, options: [])</pre><pre>// json is optional (Any?)</pre><p>This gives you plenty of flexibility when it comes to handling errors. You can pick the right try variant according to situation.</p><h3>Conclusion</h3><p>While optionals seem a very basic feature in Swift, it is there for a reason and should be used appropriately. I’ve seen developers overlook this feature and repeatedly make same mistake of accessing nil in production code. A good use of optionals make your code more readable and expressive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e6a2d30d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>