<?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 Max Althoff on Medium]]></title>
        <description><![CDATA[Stories by Max Althoff on Medium]]></description>
        <link>https://medium.com/@maxalthoff?source=rss-6aa6c8665d2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NoTOjfT7HhZmqO4B.</url>
            <title>Stories by Max Althoff on Medium</title>
            <link>https://medium.com/@maxalthoff?source=rss-6aa6c8665d2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:01:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maxalthoff/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[A Defense of Forced Unwrapping]]></title>
            <link>https://medium.com/@maxalthoff/a-defense-of-forced-unwrapping-be3820e348ad?source=rss-6aa6c8665d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3820e348ad</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Max Althoff]]></dc:creator>
            <pubDate>Tue, 19 Jul 2016 01:07:17 GMT</pubDate>
            <atom:updated>2016-07-19T15:48:39.458Z</atom:updated>
            <content:encoded><![CDATA[<p>Perhaps the single most defining feature of Swift is its overall focus on safety. This safety covers the type system, naturally, but also importantly assists the developer in ensuring the existence of a value at a property’s point of use. In those situations where it makes sense for a property to contain no value at all, the Optional type (along with a few handy pieces of syntactic sugar) allows us to safely check for the presence of a value, and then act in accordance with the needs of our app. And in all other cases (the default, ideally), we can make use of non-Optional types and avoid having to worry about whether our properties contain usable data or not, because the compiler ensures that they must.</p><p>And this is all pretty amazing stuff! But Swift’s focus on safety has also generated a troubling mentality in the community, by which a certain feature has been deemed “unsafe,” treated as a near-universal code smell, and had its (in my view) totally valid and essential meaning dismissed. I’m talking, of course, about the dreaded <strong>forced unwrap</strong>.</p><p>First, let’s take a quick look at some code snippets illustrating all of the major ways to deal with Optional types. There’s <strong>if-let unwrapping</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d9ef52bc43eb7345799e8fb9003888/href">https://medium.com/media/b4d9ef52bc43eb7345799e8fb9003888/href</a></iframe><p><strong>Nil coalescing</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd93710b5aa6c8c9cfcbda9994b77f50/href">https://medium.com/media/cd93710b5aa6c8c9cfcbda9994b77f50/href</a></iframe><p><strong>Optional chaining:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a63accc1a0c601c400ff0aec0032e39/href">https://medium.com/media/6a63accc1a0c601c400ff0aec0032e39/href</a></iframe><p><strong>Forced unwrapping</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7b593491499b82dc778e387f3ee6c94/href">https://medium.com/media/d7b593491499b82dc778e387f3ee6c94/href</a></iframe><p>The argument against <strong>forced unwrapping</strong> turns upon the notion that it is the only inherently <em>unsafe</em> method for unwrapping a value that may be present within an Optional. Which is to say, if you attempt this method and the Optional contains no value, your app will crash.</p><p>But what I’d like to suggest — and what I feel gets lost in all of the (well-intentioned) mania about safety within the Swift community — is that forced unwrapping, like all of the other unwrapping methods, conveys a unique and valid meaning to the reader of a piece of code, and that we do ourselves a disservice by suggesting that forced unwrapping is merely a product of reckless corner-cutting or laziness on the part of the programmer. To illustrate, let’s walk through the implied meanings of the unwrapping methods:</p><p><strong>If-let:</strong> <em>“I want to perform some (perhaps complex) action with the value contained in this Optional, so if it contains a value, do something with the value, otherwise perform a different action.”</em> (There need not be an otherwise here, but I’ve included one for the sake of completeness.)</p><p><strong>Nil coalescing:</strong> <em>“I fundamentally care that this expression resolves to a value, so if this Optional type contains a value, use that value, otherwise use some default value of my choosing.”</em></p><p><strong>Optional chaining:</strong> <em>“If this Optional type contains a value, then access the value, but at the end of the day, I don’t really care whether this gets done or not, because it’s not essential to the core operation or functionality of the program.”</em></p><p><strong>Forced unwrapping:</strong> <em>“This Optional type may not begin with a value, but by the time I use it here, I expect it to have a value, and beyond that, it absolutely needs to have a value in order for the core functionality of my program to be intact. I would expect my program to crash if there is no value, because there is no way to handle this situation gracefully.”</em></p><p>I’ve noticed that many in the Swift community suggest in rather strong terms that forced unwrapping is to be avoided at all costs, even going so far as to recommend not using implicitly unwrapped IBOutlet properties (which are, for all intents and purposes, guaranteed by the system to be hooked up properly and accessible upon the loading of an app). The underlying assumption seems to be that the most important thing, at all times, is to ensure that one’s perceived competence as a programmer is always protected, and that the best way to do this is to make it impossible for your program to crash at all. Because forced unwrapping allows for runtime crashes to occur, it’s written up as a forbidden art, and its underlying meaning is dismissed.</p><p>Students of Swift are often told to replace forced unwrapping with optional chaining. But if we investigate what you are telling yourself and other readers of your code when you use it (<em>“It literally does not matter whether this expression resolves or not”</em>), it becomes clear that this is often not the meaning we intend at all. I’d wager that, much of the time, we <em>do</em> actually care whether the expression we’re writing resolves to a value, a successful method call, etc. The core functionality of our program depends on it. If this is the case, doesn’t it make more sense, in terms of the meaning being conveyed to ourselves and others, to use forced unwrapping? To say, in other words, <em>“Yes, I fully expect there to be a value here, and if there isn’t one, that means there has been a catastrophic failure”</em>? It seems to me that this is an extremely useful bit of self-documentation.</p><p>Which isn’t to say that forced unwrapping should be commonplace throughout your average program. I wouldn’t hesitate to categorize this as a code smell if it’s clear that a program is absolutely littered with forced unwrappings which could have been eliminated via more elegant design. Moreover, one’s expectation that a force unwrapped Optional will contain a value at its point of use should not be a matter of <em>wishful thinking</em>, but ideally the result of extensive testing, as well as a keen understanding of the program’s flow.</p><p>The argument I’m making is that, before we render a language feature taboo in the name of “safety,” we should first pay attention to what its meaning is, and to what we potentially lose by dismissing it wholesale.</p><p><strong>Edit (7/19/2016):</strong> It’s worth noting that I’m not trying to recommend “best practices” or dictate what should or should not fly on a large team project written in Swift. There clearly do exist good reasons for wanting to minimize or stay away from forced unwrapping entirely. My point is directed more at the notion of evaluating what we <em>mean</em> by utilizing an unwrapping method, and to acknowledge that forced unwrapping <em>means</em> something specific, unique, and genuinely useful in relation to the other methods at our disposal. We should be teaching people this meaning, not concealing it in the assertion that forced unwraps are a dark art.</p><p>Another point I’m trying to make is that we sometimes suggest bad practices (for example, that people use optional chaining even if they don’t intend for non-execution to be a valid outcome) merely because they won’t <em>directly</em> cause a crash, and that this is a deeper ramification of putting the meaning of our code on the back burner, in favor of a safety-first mentality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3820e348ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Class Initializers & Inheritance: A Metaphor]]></title>
            <link>https://medium.com/@maxalthoff/swift-class-initializers-inheritance-a-metaphor-419eb52535d4?source=rss-6aa6c8665d2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/419eb52535d4</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Max Althoff]]></dc:creator>
            <pubDate>Sat, 30 Apr 2016 20:55:36 GMT</pubDate>
            <atom:updated>2016-04-30T21:48:56.494Z</atom:updated>
            <content:encoded><![CDATA[<p>Perhaps one of the most frustrating aspects of Swift is learning how and when to write class initializers. This is because one of the core mandates of the language— that every property of a class instance contain a value by the end of initialization — requires the compiler to be very strict about the entire step-by-step procedure of initialization. What I found most confusing at the beginning of my Swift studies (and I’m sure many others can empathize) were all of the seemingly arcane rules about when subclasses would or would not inherit initializers.</p><p>It’s gotten to the point where many in the community actively encourage learners to avoid creating initializers, and instead to employ crafty workarounds with default values, Optionals, and lazy variables. And while these methods are indeed useful, and many times preferable to the use of initializers, I’m the kind of person who feels that <em>things aren’t quite right</em> so long as I remain confused about a basic element of a larger topic. The fact is, everybody will have to use initializers at some point in their Swift programming lives. It’s better to understand what you’re doing than it is to rely on Xcode to fix the problem, or to forego initializers in situations where they genuinely are the best solution simply because they’re painful to wrap your head around.</p><p>When I have trouble grasping a seemingly difficult topic, what I like to do is find a real-world situation or circumstance to help me conceptualize it. To that end, I’ve come up with a metaphor encapsulating how class initializers work, specifically in the case of inheritance.</p><h4>Front Matter</h4><p>Before we dive into the metaphor itself, a brief introduction to the most basic case of class initialization is necessary. Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b809b610d9973582b066d8aeb2c8155/href">https://medium.com/media/8b809b610d9973582b066d8aeb2c8155/href</a></iframe><p>In the BaseHumanBeing class, we have two properties. Because those properties are set to default values, and there are no initializers explicitly declared within the class, we receive a free initializer, <strong>init()</strong>, which is invoked like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b63a27b0ac6a035e9929601cd355f9ee/href">https://medium.com/media/b63a27b0ac6a035e9929601cd355f9ee/href</a></iframe><p>If we employ any of a number of techniques to avoid having to write our own initializers, <strong>init()</strong> is the one we’ll be using most of the time to create instances of our classes. It’s when we start adding custom initializers and writing subclasses that things get hairy. But I think you’ll see that it’s fairly simple to understand how initializers work in more complex scenarios by applying the following concept model to the process.</p><h4>Class Initialization Is All About Growing Up</h4><p>To fit in with the metaphor, let’s start by rethinking our BaseHumanBeing class more specifically as an Adult:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/127e67dea64bee06624f9ab46398230d/href">https://medium.com/media/127e67dea64bee06624f9ab46398230d/href</a></iframe><p>We can create an instance of the Adult class like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c53122e5da06dcfdd71b4d31d498aa6/href">https://medium.com/media/8c53122e5da06dcfdd71b4d31d498aa6/href</a></iframe><p>The only differences between this class and the BaseHumanBeing class shown earlier are that Adult has not given its properties default values, and has declared its own initializer. To be precise, Adult <em>had to declare its own initializer</em> because it didn’t employ any other means to provide its properties with default values. Moreover, because Adult declared its own initializer, <em>it no longer receives the </em><strong><em>init()</em></strong><em> method</em> that it would otherwise have gotten for free:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc62532e7b92aa6e763319ead6c6aa5b/href">https://medium.com/media/dc62532e7b92aa6e763319ead6c6aa5b/href</a></iframe><p>The Adult is now on its own in the world, and has to begin doing things for itself. The <strong>init(name:age:)</strong> method is Adult’s <em>designated initializer</em>, the primary means by which it can follow through on this mandate. But Adult can also have <em>convenience initializers</em>, customized shortcuts that ultimately call on <strong>init(name:age:)</strong>, allowing the process of initialization to be carried out more, well, conveniently:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4341e9bcb5623469f421549258bbc60/href">https://medium.com/media/d4341e9bcb5623469f421549258bbc60/href</a></iframe><p>Adult now has a convenience initializer, which takes only a name parameter, and calls the designated initializer with a default age parameter in order to ensure that all properties of the Adult class are properly filled in. As expected, we now have a total of two ways to create an Adult instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/884be21dd1e787a49538deaef521f54f/href">https://medium.com/media/884be21dd1e787a49538deaef521f54f/href</a></iframe><p>The important thing to remember here is that “adult” classes (base or root classes which declare their own initializers) <em>must do for themselves</em>. They can’t rely on any sort of implied defaults like <strong>init()</strong> to carry the load (though they may redefine <strong>init()</strong> as a convenience initializer).</p><h4>The Childhood Phase</h4><p>For many, learning how initializers work in “adult” Swift classes is hard enough, but the real confusion seems to set in when inheritance enters the picture. Let’s set up an example now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21da71829ad5027382c48b4a48ce6261/href">https://medium.com/media/21da71829ad5027382c48b4a48ce6261/href</a></iframe><p>That was easy! And now let’s create Child instances using every initializer at our disposal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06365ed3382480844dd5866fdb45603f/href">https://medium.com/media/06365ed3382480844dd5866fdb45603f/href</a></iframe><p>As you can see, our Child — a completely blank subclass of Adult — not only inherits Adult’s properties, as expected, but every one of its initializers, as well. There were two ways to instantiate an Adult, and there are two ways to instantiate a Child. The important point here is that “child” subclasses (classes that don’t implement any of their own initializers) <em>get everything done for them</em> in the world of initialization.</p><p>This is, of course, analogous to how young children in the real-world are, in general terms, solely cared for by their parents. Young kids don’t take care of themselves because they lack the required knowledge, capability, and resources for doing so. But just as children take on more responsibility with age, subclasses take on more responsibility as they begin handling aspects of their own initialization.</p><h4>The Adolescent Phase</h4><p>Let’s simulate the “aging-up” of our subclass now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a53637eb464ee2617f5db2e27adbf251/href">https://medium.com/media/a53637eb464ee2617f5db2e27adbf251/href</a></iframe><p>Here we have a new Adolescent class, which again inherits from the Adult class. The main difference is that this class has updated its abilities and now contains its own convenience initializer. Let’s look at all the ways we can initialize Adolescent objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/206848825fb52b35b7cfe46b38d9273b/href">https://medium.com/media/206848825fb52b35b7cfe46b38d9273b/href</a></iframe><p>You’ll notice that Adolescent contains a total of three initializers: it’s own convenience initializer <strong>init(age:)</strong>, and the two initializers from the Adult class. Just as most teenagers in the real world can take on new responsibilities without losing access to shelter, food, and other resources provided by their parents, <em>a subclass can implement its own convenience initializers without losing access to initializers from the superclass</em>.</p><p>Note: Inside <strong>init(age:)</strong>, we call <strong>self.init(name:age:)</strong> instead of <strong>super.init(name:age:)</strong> because we have inherited Adult’s designated initializer. The compiler requires us to delegate to our own inherited version of the method.</p><h4>Leaving the Nest</h4><p>If you look closely at the above code, you’ll notice that our inherited initializers have produced strange results in a couple of cases, due to the fact that inappropriate defaults have been applied to our subclasses. Our Child and Adolescent instances should not, by definition, ever be “aged” 22. To spin out the metaphor, our subclasses have outgrown the parental doting of the Adult class. Nobody wants to be spoon-fed or told to clean her room after a certain age. So let’s model a subclass of Adult which has officially left the nest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49691099370d0aa5c42bf261b2648418/href">https://medium.com/media/49691099370d0aa5c42bf261b2648418/href</a></iframe><p>You can see that our NestLeaver class contains its own initializer, just like Adolescent did. Now let’s take a look at all the ways we can legally initialize one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5704141da523296ff0471cdeb06a4d5e/href">https://medium.com/media/5704141da523296ff0471cdeb06a4d5e/href</a></iframe><p>Huh? Adolescent had three ways to initialize, but NestLeaver only has one. What’s going on here?</p><p>Well, notice that, while our Adolescent class, which provided its own <em>convenience</em> initializer, retained access to all of the Adult class’s initializers, because NestLeaver provides a <em>designated</em> initializer, it unceremoniously <em>loses access to all of Adult’s initializers</em>. To tie in the metaphor: just as most grown-ups cannot readily expect ongoing assistance from their parents at the drop of a hat, a subclass which declares its own designated initializer cannot rely on access to <em>any</em> of its superclass’s initializers.</p><p>This is not so different, in the end, from our earlier case of BaseHumanBeing, which lost access to the default <strong>init()</strong> method after declaring its own designated initializer. In the world of Swift, when a class takes on more direct responsibility for initializing itself, the compiler holds it to that promise, like the strictest of parents.</p><p>Note 1: In <strong>init(name:age:job:)</strong>, we call <strong>super.init(name:age:)</strong> because we no longer inherit <strong>init(name:age:)</strong> from Adult, and it therefore no longer exists on <strong>self</strong>.</p><p>Note 2: It’s worth pointing out that, if NestLeaver were to explicitly <strong>override</strong> Adult’s designated initializer, it would retain access to all of Adult’s convenience initializers. But, by striking off on its own and creating a unique designated initializer, NestLeaver has foregone that possibility, and must handle all initialization by itself.</p><h4>Conclusion</h4><p>I hope this article, and the metaphor contained within it, proved helpful in your understanding of class initialization and its intersection with inheritance in Swift. Sometimes, the more finicky aspects of a programming language (i.e. the ones that cause red dots to appear in Xcode) can seem impermeable. But one of the things I love about Swift is how, once I understand what’s really going on, those finicky parts usually start to feel a lot more reasonable and logical. The compiler is incredibly strict, but nevertheless it’s got a good block on its shoulders. You can’t say that about just <em>any</em> programming language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=419eb52535d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>