<?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 Tammo Freese on Medium]]></title>
        <description><![CDATA[Stories by Tammo Freese on Medium]]></description>
        <link>https://medium.com/@tammofreese?source=rss-84cc0d5dfb3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DPYORs30eKw8mX8yhxF8Ww.jpeg</url>
            <title>Stories by Tammo Freese on Medium</title>
            <link>https://medium.com/@tammofreese?source=rss-84cc0d5dfb3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 06 May 2026 12:38:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tammofreese/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[Safely Decoding Enums in Swift]]></title>
            <link>https://medium.com/mobimeo-technology/safely-decoding-enums-in-swift-1df532af9f42?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1df532af9f42</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[keyeddecodingcontainer]]></category>
            <category><![CDATA[decodable]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Fri, 30 Apr 2021 14:02:44 GMT</pubDate>
            <atom:updated>2021-04-30T14:47:07.035Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9taVgILJPjJnOk-CWaU2Q.jpeg" /></figure><p>In Swift, we can make most types decodable by adding the Decodable protocol. While Swift’s default decoding is sufficient in most cases, it leads to issues if simple enumerations are extended later on.</p><p>This article demonstrates different approaches how to work around this issue, and highlights the advantages and disadvantages of each approach.</p><h3>The Problem</h3><p>Let’s say we are working on an app that allows you to book and pay for different modes of transportation, and we would like to configure from the backend which transport modes and payment methods are shown, and in which order.</p><p>We could have an enum for the transport modes, and one for the payment methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc30fa1ee23d00ba297ad5e0a773038/href">https://medium.com/media/2bc30fa1ee23d00ba297ad5e0a773038/href</a></iframe><p>The app config we get from the backend could then include two arrays of these enums:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b1445933e7c7519b5175ae23480a77e/href">https://medium.com/media/2b1445933e7c7519b5175ae23480a77e/href</a></iframe><p>To reduce the noise in the upcoming examples, we introduce a helper method to decode a string containing JSON to a given type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78dd5bb56f7276b3360193ba75febc1e/href">https://medium.com/media/78dd5bb56f7276b3360193ba75febc1e/href</a></iframe><p>Let’s make sure everything works as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7d94d095c2763245d1f8705baf0f20c/href">https://medium.com/media/f7d94d095c2763245d1f8705baf0f20c/href</a></iframe><p>In new versions of the app, we could add new cases to the enums. We may extend the supported transport modes with a case rideHailing, and/or the payment methods with a case sepa. If our backend sends the new cases to the old version, decoding of the app config will fail:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5353cf1d620f00fe6fce272898f92dbc/href">https://medium.com/media/5353cf1d620f00fe6fce272898f92dbc/href</a></iframe><p>We could make sure our backend does only send the new values to the newer clients, still that’s a risk: accidentally sending a payload with just one unexpected value for any of the enums will break the decoding of the whole app config. This is different to adding additional keys in the JSON object, which are ignored in decoding.</p><p>Let’s explore options on how to work around the issue. The goal is to skip unknown enum cases when decoding.</p><h3>Solutions Using Custom Decoding</h3><p>When we add Decodable to a type, we get a default implementation of the decoding initializer, that is a method with the signature init(from decoder: Decoder) throws .</p><h4>Custom Decoding Initializer</h4><p>Providing our own decoding initializer gives us complete control over how decoding is handled. Inside the initializer, we first decode our enums to arrays of the underlying raw value type, then use compactMap to get rid of any values for which we have no mapping in our enums. To implement this custom decoding, we have to provide an enum for the coding keys as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2928e858bd85eec108b26a1a2c47a0c5/href">https://medium.com/media/2928e858bd85eec108b26a1a2c47a0c5/href</a></iframe><p>Decoding now skips the unknown enum cases like we wanted:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c462951c1f7dc961cd4ab39fd458dd36/href">https://medium.com/media/c462951c1f7dc961cd4ab39fd458dd36/href</a></iframe><p>The disadvantage of this solution is that whenever we add properties to the app config, we have to change it in two places now: add the property to CodingKeys, and decode it by hand in init.</p><h4>Parse underlying Raw Values and Compute the Arrays</h4><p>Instead of defining a custom decoder, we can use the CodingKeys to map the arrays to private properties with the respective underlying raw value type, then compute the enum array properties based on the private properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d24601da8f3af004efe3c49d856da09/href">https://medium.com/media/7d24601da8f3af004efe3c49d856da09/href</a></iframe><p>Decoding gives us the same results as before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9c4a4c51dd243098e266ff5c326864f/href">https://medium.com/media/d9c4a4c51dd243098e266ff5c326864f/href</a></iframe><p>The solution is quite straightforward, and we don’t need a custom initializer anymore. We still have to declare the CodingKeys though, so when adding new properties to the app config, we need to add these to the coding keys. Also, the properties are computed which carries a performance penalty, and forces us to declare them with var instead of let .</p><p>We could work around the repeated computation by using lazy properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f0f60457ccc5bb113a809a6458a488/href">https://medium.com/media/54f0f60457ccc5bb113a809a6458a488/href</a></iframe><p>But then accessing the lazy properties mutates the struct, so when accessing the properties, the decoded app config itself needs to be declared with var instead of let:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3d8ce66078aa5b964dd1289fd5e6519/href">https://medium.com/media/f3d8ce66078aa5b964dd1289fd5e6519/href</a></iframe><p>All approaches we saw so far share the disadvantage of duplicating the logic for mapping the enums. Let’s explore solutions on the property level.</p><h3>Solutions on Property Level</h3><p>We want the properties with the enum arrays to be decoded differently to the default behavior. To achieve that, we can use a custom type as the property, instead of using an array directly.</p><h4>Wrap the Property in a Custom Type</h4><p>We put the logic for skipping unknown cases in a custom decoding initializer for our wrapper type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f54904b604ad54cfb31fc626700d9006/href">https://medium.com/media/f54904b604ad54cfb31fc626700d9006/href</a></iframe><p>In the app config, we use our custom wrapper type instead of arrays:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59fa35ad574f61e2b94b6d2bb846ab37/href">https://medium.com/media/59fa35ad574f61e2b94b6d2bb846ab37/href</a></iframe><p>After decoding, we now need to access the values property of our custom type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e58554176a0ecbc49aac39c3f9a36a98/href">https://medium.com/media/e58554176a0ecbc49aac39c3f9a36a98/href</a></iframe><p>Compared to the solutions before, there are a couple of advantages: We don’t have to define CodingKeys or a custom initializer on the app config, so when adding properties to the app config we don’t need additional code changes. Also, we removed the duplicated logic of ignoring the unknown values — there is only one compactMap instead of two. We can reuse this wrapper type wherever we like.</p><p>One disadvantage is the wrapper type bleeds out to all usages of the properties: Instead of appConfig.transportModes or appConfig.paymentMethods, we have to use appConfig.transportModes.values or appConfig.paymentMethods.values.</p><h4>Use a Property Wrapper</h4><p>In newer versions of Swift, we can declare a property wrapper instead.</p><p>Note there is not much change to the struct we had before — we add @propertyWrapper, and rename the variable containing the value to wrappedValue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e88916e17ae6fd34f19b802174b039c/href">https://medium.com/media/3e88916e17ae6fd34f19b802174b039c/href</a></iframe><p>The types of the properties are back to being arrays of enums:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5fa27ba878050aba2998a16ff40f27/href">https://medium.com/media/1c5fa27ba878050aba2998a16ff40f27/href</a></iframe><p>Accessing the decoded properties works directly again, no more .values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd8d7b7a243ae89a549be750afa8f207/href">https://medium.com/media/cd8d7b7a243ae89a549be750afa8f207/href</a></iframe><p>A slight drawback is we have to declare the properties asvar, as properties using property wrappers cannot be declared as let.</p><h3>Solutions on Type Level</h3><p>The previous two solutions handled the skipping of unknown values at the property level. It may be more practical to skip on the type level though: Whenever we declare a property of type [TransportMode] or [PaymentMethod] in a decodable type, we may want to get the skipping of unknown cases for free, without having to use a property wrapper each time.</p><h4>Extend KeyedDecodingContainer</h4><p>To change the decoding behavior for decoding a type for a key, we can extend KeyedDecodingContainer. That type makes the encoded properties of a decodable type accessible by keys.</p><p>Among other methods KeyedDecodingContainer has methods of the signature decode(_, forKey: _). If we add overloads of this signature for more special types than are covered by the existing decode methods, they will be used in generated decoding initializers.</p><p>To not interfere with the code of the other examples, we define the extension for new types TransportMode5, PaymentMethod5, and AppConfig5:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3898bb5e94af72c14e8909944434170/href">https://medium.com/media/f3898bb5e94af72c14e8909944434170/href</a></iframe><p>We add two extensions, one for each enum array type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efa997da3fd9933c70f6c7b26d48be28/href">https://medium.com/media/efa997da3fd9933c70f6c7b26d48be28/href</a></iframe><p>And let’s make sure decoding succeeds:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/895af8dea931d3da3fc6b07467c5b802/href">https://medium.com/media/895af8dea931d3da3fc6b07467c5b802/href</a></iframe><p>When the decoding initializer for AppConfig5 is generated, our two customedecode methods are used as they define how to decode the types [TransportMode5] and [PaymentMethod5].</p><p>A disadvantage is we ended up with code duplication again. Also, there is no indication—neither on the properties nor on the types—that arrays of transport modes and payment methods are handled in a non-default way.</p><h4>Make the KeyedDecodingContainer Extension Reusable</h4><p>Let’s make the extension reusable. First, we declare a protocol to mark the types for which we want to skip unknown cases in array decoding. We only allow the protocol to be added on types that fulfill our current requirements: We want a type that conforms to both RawRepresentable and Decodable, and the raw value needs to be decodable as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ca025306223a50e3b8a56c93f99e98/href">https://medium.com/media/c5ca025306223a50e3b8a56c93f99e98/href</a></iframe><p>Then, we extend KeyedDecodingContainer with a decode method that applies only to arrays of types conforming to our protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e695efac7d0ec4758460edf5927f3b94/href">https://medium.com/media/e695efac7d0ec4758460edf5927f3b94/href</a></iframe><p>Now, all we have to do is to let the types conform to our protocol.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ad591814fc89d734573684414abed6/href">https://medium.com/media/78ad591814fc89d734573684414abed6/href</a></iframe><p>And unknown enum cases are skipped again when decoding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8823f28579bce7ef8867e24ea41faddb/href">https://medium.com/media/8823f28579bce7ef8867e24ea41faddb/href</a></iframe><h3>Which Solution to Prefer?</h3><p>We saw six approaches on how to solve the issue. Which one should we prefer? I think there are a few we can rule out as candidates:</p><ul><li>Custom decoding (solutions 1+2) forces us to write extra code when adding properties to the app config.</li><li>Of solutions on the property level (solution 3+4), I prefer the property wrapper: while it needs the change from let to var, it does not influence how call sites look.</li><li>Of the solutions on type level with KeyedDecodingContainer (solutions 5+6), I prefer making the extension reusable: it has no code duplication, and the protocol at least gives a hint that the type is handled in a special way.</li></ul><p>Two solutions remain: on property level using a property wrapper (solution 4), and on type level using a marker protocol (solution 6).</p><p>I like the marker protocol solution because it declares our intent on the type: if we have multiple places where an array of a certain enum is returned, we only need one declaration on the type, and not use the property wrapper multiple times. So no duplication. On the other hand, we may <em>want</em> the duplication in this case: the changed decoding is explicitly visible on the property itself.</p><p>If I would have to decide for one winner, I would go for the property wrapper, but the marker protocol is a close second.</p><p>Whichever solution you prefer in your code, if you end up needing more and more of workarounds for Swift’s default decoding, there are libraries out there which may help. One example is <a href="https://github.com/airbnb/ResilientDecoding">AirBnB’s ResilientDecoding</a>, others are just an internet search away.</p><h3>Bonus Track: Increase Reusability of the Marker Protocol Solution</h3><p>Still here? Good! You may have noticed we had to add an awful lot of constraints on the SkipUnknownCasesInArrayDecoding protocol. Wouldn’t it be nice if we could apply it to any decodable type?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0128e7d4db986189792b2c1f3079ef6/href">https://medium.com/media/c0128e7d4db986189792b2c1f3079ef6/href</a></iframe><p>Turns out this is possible. We can use the nestedUnkeyedContainer(forKey:) method to get a data structure that allows us to go through all elements in the array. We collect all elements where the decoding succeeds in a result array. The elements where decoding fails we skip by decoding them to an empty struct — there decoding always succeeds:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce0c222c6ab6c9d36cf95cd6089a4a3b/href">https://medium.com/media/ce0c222c6ab6c9d36cf95cd6089a4a3b/href</a></iframe><p>And that’s it for the bonus track. Happy Decoding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1df532af9f42" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobimeo-technology/safely-decoding-enums-in-swift-1df532af9f42">Safely Decoding Enums in Swift</a> was originally published in <a href="https://medium.com/mobimeo-technology">Mobimeo Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What If Your Designers Want a Baseline Grid on iOS?]]></title>
            <link>https://medium.com/mobimeo-technology/what-if-your-designers-want-a-baseline-grid-on-ios-d5234c7b52c0?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5234c7b52c0</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[dynamic-type]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[baseline]]></category>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 08:18:50 GMT</pubDate>
            <atom:updated>2021-04-09T08:42:23.274Z</atom:updated>
            <content:encoded><![CDATA[<p>In typography, there is the notion of a <em>baseline grid</em>: All the baselines of a text are aligned on invisible lines. Baseline alignment goes back at least 100 years: It is part of the Swiss Style/International Typographic Style.</p><p>Baseline alignment still goes strong today: On the web, CSS allows baseline alignment; on Android, baseline alignment is part of Material Design.</p><h3>📱What about iOS?</h3><p>Baseline alignment is not the default on iOS: A label takes the space needed for the content, the baselines do not lie on an invisible grid.</p><p>At one point, we were asked by our designers whether it would be possible to do baseline alignment on iOS. Let’s concentrate on UILabel, as that is used to display text in most cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yi_Gs2xXU9BqgLeM" /></figure><p>What complicates things is Dynamic Text. If an app uses that for accessibility, the designers have a choice of eleven predefined text styles (like headline, caption, …). The sizes of these text styles are not fixed, but change based on the user’s choice of the content size category. There are twelve content size categories: seven ranging from XS to XXL, and five even larger sizes for accessibility.</p><h3>🥅 Goal</h3><p>The goal of this article is to give an idea how to achieve baseline alignment for UILabel, working for Dynamic Type (that means all 11 * 12 = 132 combinations), and for multi-line labels.</p><h3>📕 Terminology</h3><p>First, let’s align on the terminology how we use it in this article.</p><ul><li>The <em>baseline</em> is the imaginary line on which the characters rest.</li><li>The <em>ascender</em> is the offset from the baseline to the font’s longest ascender, the topmost point of any character, including space for accents/umlauts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*XYqfR2fpehwv0RKw5YLv4w.png" /></figure><ul><li>The <em>descender</em> is the offset from the baseline to the font’s longest descender.</li><li>The <em>line height</em> is the height of a line of text, that is the ascender plus the descender.</li><li>The <em>leading</em> is the extra distance between two lines of text. It is pronounced “ledding” and not “leeding”, as in hand typesetting it was done with strips of the metal lead.</li></ul><h3>😕 A Bit of Confusion</h3><p>Some of the terminology is not used consistently.</p><ul><li>While the ascender for the fonts used in Dynamic Text includes space for accents and umlauts, it is often shown smaller in illustrations (<a href="https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html#//apple_ref/doc/uid/TP40009459-CH5-SW5">Font handling, Apple Developer docs</a>)</li><li>The line height is often shown including the leading, but it does not include the leading on iOS (<a href="https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html#//apple_ref/doc/uid/TP40009459-CH5-SW5">Font handling, Apple Developer docs</a>)</li><li>The leading is the extra distance between two lines of text, but sometimes (mainly in electronic typesetting) it is used to describe the full distance between two lines of text instead (<a href="https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/typography/">Visual design typography, Apple Developer docs</a>)</li></ul><h3>🔎 Implementation Details</h3><p>Let’s see how to approach this in code.</p><h4>🧱 Setup</h4><p>We want to make sure our assumptions hold for all dynamic type fonts. There are 12 content size categories a user can choose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb9b57e17b41eb1f2a585d82abbd41c0/href">https://medium.com/media/cb9b57e17b41eb1f2a585d82abbd41c0/href</a></iframe><p>We can use 11 different text styles for dynamic type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05b7592b56fc7ce87cb94567215f87a8/href">https://medium.com/media/05b7592b56fc7ce87cb94567215f87a8/href</a></iframe><p>With 12 content size categories and 11 text styles, we end up with 132 combinations for which we have to check everything works fine. Let’s build an array of those fonts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e18eca75020c0244e5ca680e6eb0db7/href">https://medium.com/media/4e18eca75020c0244e5ca680e6eb0db7/href</a></iframe><p>To see whether the height of a label matches our expectations, we add a helper method to give us the height of a label for a given font, number of lines, and an optional line spacing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21f104b3d3f64e7e560e313e10004fd/href">https://medium.com/media/c21f104b3d3f64e7e560e313e10004fd/href</a></iframe><p>As our goal is to place something on a grid, let’s add a helper method to have an easy way to round up a number to the next multiple of a given unit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e62f4dfeed6d1ad0317957cf52489c7/href">https://medium.com/media/3e62f4dfeed6d1ad0317957cf52489c7/href</a></iframe><h4>📐 Validate Assumptions on Font Metrics</h4><p>The ascender is always a positive value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480325de718ddec27c9078cac1d9d40a/href">https://medium.com/media/480325de718ddec27c9078cac1d9d40a/href</a></iframe><p>The descender is always a negative value (as it goes in the opposite direction from the baseline in comparison to the ascender):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc4c9796109a202d9cdd0f91dcc7d5f2/href">https://medium.com/media/cc4c9796109a202d9cdd0f91dcc7d5f2/href</a></iframe><p>The line height is always the sum of the ascender and the negated descender:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96680c98a75249ba0fc97c9501b8bb5e/href">https://medium.com/media/96680c98a75249ba0fc97c9501b8bb5e/href</a></iframe><h4>☝️ Validate Assumptions for Single Line Labels</h4><p>Contrary to what we may expect at first, the height of a label of a single line of text is <strong>not</strong> always equal to the line height of the font:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a689d97e2cb64f6c0cf6c42efff8a25/href">https://medium.com/media/7a689d97e2cb64f6c0cf6c42efff8a25/href</a></iframe><p>To get the height of the label, we have to round up the line height to the next “pixel”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afedf6e29dd6bcc33f4c05490d224041/href">https://medium.com/media/afedf6e29dd6bcc33f4c05490d224041/href</a></iframe><h4>🎯 Reaching the Goal for Single Line Labels</h4><p>In iOS’ Auto Layout, we can anchor to the first and the last baseline of a label via firstBaselineAnchor/lastBaselineAnchor. Except for a tiny bit of rounding up, the single line label has the same height as the line height.</p><p>If we have a top anchor that is on the grid, we can add a constraint that sets the first baseline of the label to that anchor plus the ascender rounded up to the grid size. That way, the baseline ends up on the grid, and as we rounded the ascender up, there is enough space for the ascender:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2124a8b2241df84143ac39aa825a846a/href">https://medium.com/media/2124a8b2241df84143ac39aa825a846a/href</a></iframe><p>If we have a bottom anchor that should end up on the grid, we can add a constraint that sets the last baseline of the label plus the (negated) descender rounded up to the grid size to that anchor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a07324b99918c9ee5262452cea5119/href">https://medium.com/media/c5a07324b99918c9ee5262452cea5119/href</a></iframe><p>So now if the top anchor is on the grid, the two constants fix the baseline and the bottom anchor to the grid. This solves the issue for single line labels. For multi-line labels, we additionally need to make sure that the distance between two baselines is a multiple of the grid unit.</p><h4>🖐 Validate Assumptions for Multi Line Labels</h4><p>The multiple of the line height rounded up to the next pixel is <strong>not</strong> always the label height.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/332291daf25d8a9c11977f8717ec0e5e/href">https://medium.com/media/332291daf25d8a9c11977f8717ec0e5e/href</a></iframe><p>To calculate the correct height, we have to take the leading into account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e144749b9874b5648f25090f44ab7499/href">https://medium.com/media/e144749b9874b5648f25090f44ab7499/href</a></iframe><p>The distance between two baselines is font.lineHeight + font.leading. To get a grid alignment for multi-line labels, we need to round that distance up to a multiple of the grid. So how can we add to the distance between two lines? lineSpacing in an attributed text’s paragraph style sounds right.</p><p>Unfortunately it’s not that easy. Here is a test adding 1.5 to the line spacing of a two-line label. There are cases where the calculation is off:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bc58ed24c10e81168d4fe64b4e65d02/href">https://medium.com/media/4bc58ed24c10e81168d4fe64b4e65d02/href</a></iframe><p>The calculation only works if the leading is less than or equal to zero:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f241e1dcbb570078bd8610a41e50b337/href">https://medium.com/media/f241e1dcbb570078bd8610a41e50b337/href</a></iframe><p>If the leading is positive, it turns out it is used as a minimum line spacing for dynamic type fonts! This is an inconsistency between the handling of negative and positive leadings. Examples:</p><ul><li>Leading -0.5 points, lineSpacing 1.5 points: 1 point between the lines</li><li>Leading +0.5 points, lineSpacing 1.5 points: 1.5 points between the lines</li><li>Leading +2 points, lineSpacing 1.5 points: 2 points between the lines</li></ul><p>To increase the line height correctly for positive leadings, we have to add positive leadings to the line spacing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d782c5184ee36b2d7ab21ef0c3bc3349/href">https://medium.com/media/d782c5184ee36b2d7ab21ef0c3bc3349/href</a></iframe><p>Now we have figured out how to reliably increase the distance between two baselines. What’s left is to set that increase to the distance between two baselines is a multiple of the grid unit.</p><h4>🎯 Reaching the Goal for Multi Line Labels</h4><p>For a label, the default distance between the baselines is the line height plus the leading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac4fa9d29441a82ce1b795df5c16c770/href">https://medium.com/media/ac4fa9d29441a82ce1b795df5c16c770/href</a></iframe><p>Our target distance between baselines is the default distance rounded up to the next multiple of the grid unit. As the constraints from the single line label handling above guarantee the first baseline to be on the grid, all the following lines will then be on the grid as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3144b6bf6e53d32c22335883135ca76/href">https://medium.com/media/e3144b6bf6e53d32c22335883135ca76/href</a></iframe><p>The line spacing we have to set is the difference between the two.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59a8c9668bba507be898ed815f45208f/href">https://medium.com/media/59a8c9668bba507be898ed815f45208f/href</a></iframe><p>But as positive leadings act as minimum line spacing, we have to add those to the line spacing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2182fe3a87bf081c473d25604858359c/href">https://medium.com/media/2182fe3a87bf081c473d25604858359c/href</a></iframe><p>Now we can use this line spacing in a paragraph style, and instead of setting the text on the label, set the attributed text with that paragraph style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebfab3d31403bbeeefa7688bb623fed/href">https://medium.com/media/bebfab3d31403bbeeefa7688bb623fed/href</a></iframe><h3>🛠 Putting It All Together</h3><p>The outcome of this experiment is that aligning to a baseline grid on iOS is possible.</p><p>You can find a playground with the code shown in this article, as well as a sample app with an implementation of a label view that aligns the text on the baselines hosted on GitHub here: <a href="https://github.com/mobimeo/ios-baseline-alignment">https://github.com/mobimeo/ios-baseline-alignment</a>. For production code, you should consider converting the assertions into unit tests, so if the behavior changes in future versions of iOS, you learn about it early enough.</p><p>The biggest learning for me was the different handling of leading for positive and negative values. Or maybe that I pronounced leading wrong for way too long. 😅</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5234c7b52c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobimeo-technology/what-if-your-designers-want-a-baseline-grid-on-ios-d5234c7b52c0">What If Your Designers Want a Baseline Grid on iOS?</a> was originally published in <a href="https://medium.com/mobimeo-technology">Mobimeo Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facets of Swift, Part 5: Custom Operators]]></title>
            <link>https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1080bc78ccc</guid>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Sun, 05 Oct 2014 20:02:54 GMT</pubDate>
            <atom:updated>2016-03-06T18:34:27.422Z</atom:updated>
            <content:encoded><![CDATA[<p>Facets of Swift is a series of articles on various aspects of the Swift programming language. At last I have found the time to write the fifth article of this series. As you may have guessed from the title, it’s about custom operators. Operators are closely related to functions, which were the topic of the previous article.</p><h3>What’s an Operator?</h3><p>Most programming languages use operators. <strong>Simply put, an operator is a symbol or phrase that represents a functionality.</strong> For example, <em>i = 1</em> in Swift uses the assignment operator <em>=</em> which has the functionality of storing the value <em>1</em> in the variable <em>i</em>. Many languages also have phrases that are operators, like <em>sizeof</em> in C, and the type-cast operator <em>as</em> in Swift.</p><h4>Arity</h4><p>An operator, or more accurately the operation represented by an operator, accepts a number of <em>operands</em> (parameters in operator lingo). The number of operands an operator accepts is called the <em>arity</em>. From Objective-C, we know operators with arity 1–3.</p><p>Unary operators represent operations with one operand. Examples in Objective-C include the negation operator <em>!</em>, the increment operator <em>++</em>, and the <em>sizeof</em> operator.</p><p>Binary operators represent operations with two operands. The majority of Objective-C’s operators are binary operators, like <em>+</em>, <em>-</em>, <em>*</em>, <em>/</em>, <em>&lt;</em>, <em>&lt;=</em>, <em>&gt;=</em>, <em>&gt;</em>, <em>==</em>, <em>!=</em>, <em>&amp;&amp;</em>, <em>=</em>, <em>+=</em>, <em>-=</em>, and so on.</p><p>Ternary operators represent operations with three operands. In Objective-C and Swift, there is only one ternary operator: The conditional expression <em>? :</em> . As it’s the only ternary operator in both languages, and as we can’t customize it, let’s focus on unary and binary operators from now on.</p><h4>Placement</h4><p>An operator can be placed in three ways relative to its operands. An unary operator can be placed on either side of the operand: Either as a <em>prefix</em>, like the negation operator in <em>!visible</em>, or as a <em>postfix</em>, like the increment operator in <em>i++</em>.</p><p>Binary operators could be placed as a prefix, postfix, or <em>infix</em> (between the operands). In Objective-C and Swift, binary operators are always placed infix. As we focus on unary and binary operators, the placement (also called <em>fixity</em>) of an operator is sufficient to determine the arity: Prefix and postfix operators are unary, infix operators are binary.</p><h4>Overloading</h4><p>Operators are often <em>overloaded</em>, meaning they work for different types. In C/Objective-C for instance, the <em>+</em> operator is overloaded to allow adding two <em>int</em> and two <em>double</em>, among others. In contrast, functions in C/Objective-C are never overloaded. To be fair, the C11 standard introduced a <em>_Generic</em> keyword which allows us to at least write a macro that emulates function overloading.</p><h4>Precedence and Associativity</h4><p>Operators have a <em>precedence</em>, and an <em>associativity</em> that determine the order in which they are executed.</p><pre>let a = 3<br>let b = 4<br>let c = a <strong>*</strong> a <strong>+</strong> b <strong>*</strong> b<br>let d = b <strong>—</strong> a <strong>+</strong> b</pre><p>Swift follows the rules we are used to from math. Multiplication has a higher precedence than addition. So the first calculation results in <em>c = (a * a) + (b * b) = 25</em>. Addition and subtraction have the same precedence, and left associativity. So the calculation is grouped from left to right, and results in <em>d = (b - a) + b = 5</em>.</p><p>Operators can either be left-associative, right-associative, or non-associative. You may wonder how non-associativity may be a good thing. Here is an example:</p><pre>BOOL a = NO;<br>BOOL b = NO;<br>BOOL c = YES;<br>if (<strong>a == b == c</strong>) {<br>    NSLog(@&quot;WAT&quot;);<br>}</pre><p>At first glance, we may expect this code to only print “<em>WAT</em>” if and only if <em>a</em>, <em>b</em>, and <em>c</em> are equal. However, <em>==</em> is left-associative in Objective-C, so <em>a == b == c</em> means <em>(a == b) == c</em>, which is true for a couple of combinations.</p><p>In Swift, <em>==</em> is non-associate, so the compiler will gives us a shiny error that a non-associative operator is adjacent to an operator of the same precedence.</p><pre>var a = false<br>var b = false<br>var c = true<br>if <strong>a == b == c</strong> {     // COMPILER ERROR<br>    println(&quot;WAT&quot;)<br>}</pre><p>I like it when a language keeps me from making stupid mistakes.</p><h4>Short-Circuit Evaluation</h4><p>A couple of operators in Objective-C and Swift provide <em>short-circuit evaluation</em>. That means an operand is only calculated if necessary. The following code will not print anything, as the result of the logical <em>&amp;&amp;</em> operator is already determined by the first operand.</p><pre>func foo() -&gt; Bool {<br>    println(&quot;foo() called&quot;)<br>    return true<br>}<br>false &amp;&amp; foo()</pre><p>Now that we have the terminology straight (unary, binary, prefix, postfix, infix, precedence, associativity, short-circuit evaluation), let’s see how we add operators in Swift.</p><h3>Adding Operators in Swift</h3><p>Objective-C does not allow us to add operators: They are hard-coded in the language. <strong>In Swift, we can define a surprisingly rich set of operators.</strong> We can use most combinations of the ASCII symbols <em>.</em>, <em>+</em>, <em>-</em>, <em>*</em>, <em>/</em>, <em>%</em>, <em>&lt;</em>, <em>=</em>, <em>&gt;</em>, <em>!</em>, <em>&amp;</em>, <em>|</em>, <em>^</em>, <em>~</em>.<em> </em>Even better, we can use a plethora of Unicode characters. Math. Arrows. Symbols. Dingbats. And more. And if that’s not enough, we can use Unicode combining characters on those characters as well.</p><p>Let’s add the operators logical negation <em>¬</em>, logical conjunction <em>∧</em>, and logical disjunction <em>∨</em> as alternatives to <em>!</em>, <em>&amp;&amp;</em>, and <em>||</em>.</p><h4>Operator Declaration</h4><p>Adding a new operator consists of two parts: We have to declare the operator, and to implement at least one function giving meaning to the operator. The logic operator ¬ is a prefix operator:</p><pre><strong>prefix operator ¬ {}</strong></pre><p>Associativity and precendence declarations go between the braces. Unary operators in Swift always take precedence over binary operators, so we aren’t allowed to specify any precedence. We are also not allowed to specify an associativity, as unary operators always cling to their operand. As a result, whenever we add a prefix or postfix operator, the braces remain empty — but they have to be there.</p><h4>Operator Implementation</h4><p>Next, we implement a function for the operator. The function name is simply the operator symbol. We have to put <em>prefix</em> in front of the function declaration, so the compiler knows which function to use even if we would later declare a postfix version of the operator as well (think <em>++i</em> vs <em>i++</em>).</p><pre><strong>prefix</strong> func <strong>¬</strong>(a: Bool) -&gt; Bool {<br>    return !a<br>}</pre><p>That’s it! Our new operator is ready for use:</p><pre>assert(¬false)<br>assert(¬(¬true))</pre><h4>Infix Operators</h4><p>Next up: The <em>∧</em> operator. A first attempt by copy-pasting and adapting the <em>¬</em> operator may look like this:</p><pre><strong>infix</strong> operator <strong>∧</strong> {}<br><strong>infix</strong> func <strong>∧</strong>(lhs: Bool, rhs: Bool) -&gt; Bool { // COMPILER ERROR<br>    return lhs &amp;&amp; rhs<br>}</pre><p>The compiler complains that the <em>infix</em> modifier is not required or allowed on function declarations. OK, let’s delete it. Then the code works — as long as we don’t try to use the operator in an expression more than once.</p><pre>assert(<strong>true ∧ true</strong>)<br>assert(<strong>¬(true ∧ false)</strong>)<br>assert(<strong>true ∧ true ∧ true</strong>) // COMPILER ERROR</pre><h4>Choosing an Associativity</h4><p>That’s because for infix operators, the default associativity is <em>none</em>. The <em>&amp;&amp; </em>operator for which our operator will be an alternative is left associative. So we declare our operator to be left associative as well, and the error goes away.</p><pre>infix operator ∧ { <strong>associativity left</strong> }</pre><h4>Adding Short-Circuit Evaluation</h4><p>Now let’s add short-circuit evaluation. The following code should not print anything.</p><pre>func foo() -&gt; Bool {<br>    println(“foo() called”)<br>    return true<br>}<br>false ∧ foo()</pre><p>But of course it does: <em>false ∧ foo()</em> differs to a function call syntactically, but is the same semantically. We can even write down the function call:</p><pre>(∧)(false, foo())</pre><p>The parentheses around the operator symbol are needed as <em>∧(false, foo())</em> would be parsed as using a prefix operator <em>∧</em> with the operand <em>(false, foo())</em>.</p><p>All arguments of a function call are evaluated before the call takes place. How can we delay the evaluation of the second parameter? We could make the second parameter a closure returning a <em>Bool</em>. If you don’t know what a closure is, think “anonymous function” or “Objective-C block-like thingy”, both are close enough to understand what’s going on.</p><pre>func ∧(lhs: Bool, rhs: <strong>() -&gt; Bool</strong>) -&gt; Bool {<br>    return lhs &amp;&amp; rhs<strong>()</strong><br>}</pre><pre>func foo() -&gt; Bool {<br>    println(“foo() called”)<br>    return true<br>}<br>false ∧<strong> { </strong>foo()<strong> }</strong><br>(^)(false, <strong>{ </strong>foo()<strong> }</strong>)</pre><p>Now <em>rhs()</em> will only be evaluated if <em>lhs</em> is true, because of the short-circuit evaluation of <em>&amp;&amp;</em>. But this comes at a price: We have to put the second argument in braces ourselves now to make it a closure. What we need is something that automatically wraps the second parameter in a closure. In Swift, that can be done by using the <em>@autoclosure</em> attribute on the parameter. Now we get real short-circuit evaluation, without having to wrap the second argument in braces.</p><pre>func ∧(lhs: Bool, rhs: <strong>@autoclosure</strong> () -&gt; Bool) -&gt; Bool {<br>    return lhs &amp;&amp; rhs()<br>}</pre><pre>func foo() -&gt; Bool {<br>    println(“foo() called”)<br>    return true<br>}<br>false ∧ foo()<br>(^)(false, foo())</pre><p>Allow me to get sidetracked here for a bit. As the last line of the example above demonstrates, the autoclosure attribute is not limited to operators syntax, but works just fine for function calls as well. One example that relies heavily on <em>@autoclosure</em> is Swift’s <em>assert</em> function.</p><pre>var error: NSError? = nil<br>assert(<strong>error == nil</strong>, &quot;error is \(error<strong>!</strong>.localizedDescription)&quot;)</pre><p>The <em>assert</em> call above gets a condition, and a message as arguments. If the message argument in the above example would be always evaluated, the code would crash: We force-unwrap error, which is <em>nil</em>. However, <em>assert</em> uses the autoclosure attribute on the message parameter, and only evaluates the closure if the condition evaluates to <em>false</em>. So we can safely use the force-unwrap in the second parameter, even though <em>error</em> is <em>nil</em>!</p><p>On the condition parameter of <em>assert</em>, the autoclosure attribute is also used. That way if we disable assertions, the condition parts stay unevaluated as well, and a compiler optimization can remove them completely.</p><p>The beauty of that is although <em>assert</em> has all these features, it can still be implemented as a Swift function! Compare that to C, where <em>assert</em> was implemented as a preprocessor macro, or to Java, where <em>assert</em> had to be added as a keyword. <strong>Swift’s autoclosure attribute allows us to write functions and operators that would require compiler changes in a couple of other languages.</strong></p><p>Back to our topic: custom operators. As we just implemented the logical conjunction <em>∧</em> , the logical disjunction <em>∨</em> is a breeze:</p><pre>infix operator ∨ { associativity left }<br>func ∨(lhs: Bool, rhs: @autoclosure () -&gt; Bool) -&gt; Bool {<br>    return lhs || rhs()<br>}</pre><p>The only problem that’s left is that we can get wrong behavior when combining our two infix operators.</p><pre>assert(<strong>true || true &amp;&amp; false</strong>)  // OK<br>assert(<strong>true ∨ true ∧ false</strong>)  // FAIL</pre><h4>Adding Precedences</h4><p>That’s because we haven’t declared precedences yet. Both operators share the same (default) precedence, and both are left associative, so the expression is evaluated as <em>(true ∨ true) ∧ false</em>. But of course we want the <em>∧</em> operator to have higher precedence, so that we end up with <em>true ∨ (true ∧ false)</em>.</p><p>In Swift, precedences are declared as numeric values from <em>0</em> to <em>255</em>. Unsurprisingly, a higher value means a higher precedence. The default precedence is <em>100</em>. As we want our operators <em>∨</em> and <em>∧</em> to be alternatives to <em>||</em> and <em>&amp;&amp;</em>, we look up the the precedence values of those two, and use the same values for our operators:</p><pre>infix operator ∧ { associativity left <strong>precedence 120</strong> }<br>infix operator ∨ { associativity left <strong>precedence 110</strong> }</pre><p>And that’s it. We have added three new operators to the language, using only a couple of lines of code:</p><pre>prefix operator ¬ {}<br>prefix func ¬(a: Bool) -&gt; Bool {<br>    return !a<br>}</pre><pre>infix operator ∧ { associativity left precedence 120 }<br>func ∧(lhs: Bool, rhs: @autoclosure () -&gt; Bool) -&gt; Bool {<br>    return lhs &amp;&amp; rhs()<br>}</pre><pre>infix operator ∨ { associativity left precedence 110 }<br>func ∨(lhs: Bool, rhs: @autoclosure () -&gt; Bool) -&gt; Bool {<br>    return lhs || rhs()<br>}</pre><p>What about operators that change the operands, like assignment operators, or a swap operator? Lets add an operator &lt;-&gt; that swaps two <em>Int</em> values.</p><pre>infix operator &lt;-&gt; {}<br>func &lt;-&gt;(inout lhs: Int, inout rhs: Int) {<br>    (lhs, rhs) = (rhs, lhs)<br>}<br> <br>var a = 42<br>var b = 23<br> <br>a &lt;-&gt; b<br>assert(a == 23 &amp;&amp; b == 42)</pre><p>You may wonder why this works. The function has <em>inout</em> parameters. Shouldn’t we need to use inout expressions, that is prefix the operands with ampersands? We can do that, but we don’t need to: While Swift requires the ampersands for function call syntax, it does not require them if we use operator syntax!</p><pre><strong>a </strong>&lt;-&gt;<strong> b</strong>        // Totally fine.<br>a &lt;-&gt; &amp;b       // Works as well. Don&#39;t do it though.<br>&amp;a &lt;-&gt; b       // Works as well. Don&#39;t do it though.<br>&amp;a &lt;-&gt; &amp;b      // Works as well. Don&#39;t do it though.<br> <br>(&lt;-&gt;)(<strong>&amp;a, &amp;b</strong>)  // Function call requires &amp; for inout parameters.<br>(&lt;-&gt;)(a, &amp;b)   // COMPILER ERROR<br>(&lt;-&gt;)(&amp;a, b)  // COMPILER ERROR<br>(&lt;-&gt;)(a, b)  // COMPILER ERROR<br></pre><h3>Overloading Operators in Swift</h3><p>After we’ve seen how to add operators in Swift, let’s see how we overload existing operators with new functionality. To understand how this works, let’s first have a look at function overloading.</p><h4>Function Overloading in Swift</h4><p><strong>In Swift, we can overload a function.</strong> That means we give it the same name as another function, but the parameters types, or the return type has to be different. The compiler then tries to infer which function we would like to use.</p><pre>func foo(<strong>i: Int</strong>) {<br>    println(&quot;foo(i: Int)&quot;)<br>}<br> <br>func foo(<strong>i: String</strong>) {<br>    println(&quot;foo(i: String)&quot;)<br>}<br> <br>foo(<strong>42</strong>)            // -&gt; &quot;foo(i: Int)&quot;<br>foo(<strong>&quot;The answer&quot;</strong>) // -&gt; &quot;foo(i: String)&quot;</pre><p>When the function to be called is ambiguous, we get a compiler error.</p><pre>func foo() -&gt; Int {<br>    return 42<br>}<br> <br>func foo() -&gt; String {<br>    return &quot;The answer&quot;<br>}<br> <br>let result = foo() // COMPILER ERROR</pre><p>In the code snippet above, <em>foo()</em> is ambiguous: Both functions are equally well suited candidates. To resolve the ambiguity, we can help the compiler in different ways. We can select the function with a cast:</p><pre>let result = (foo <strong>as () -&gt; Int</strong>)()</pre><p>That’s not really pretty. A more readable variant is to make the compiler infer the function by casting the result type:</p><pre>let result = foo() <strong>as Int</strong></pre><p>In my opinion, the best way in this case is to give the receiving variable the correct type:</p><pre>let result<strong>: Int</strong> = foo()</pre><p>Not only is this the shortest variant, but it clearly states what we want: We want to get an <em>Int</em> result from <em>foo()</em>.</p><p>If you are used to Objective-C, note that the selection of the function is done statically, not dynamically at runtime.</p><pre>class A {}<br>class B: A {}<br> <br>func foo(<strong>a: A</strong>) {<br>    println(&quot;A&quot;)<br>}<br> <br>func foo(<strong>b: B</strong>) {<br>    println(&quot;B&quot;)<br>}<br> <br>var <strong>a: A = B()</strong><br>foo(<strong>a</strong>)           // Prints &quot;A&quot;, not &quot;B&quot;!</pre><p>Although the object <em>a</em> is an instance of <em>B</em> at runtime, the selection of the function is made at compile-time based on the type of the variable <em>a</em>.</p><h4>Operator Overloading in Swift</h4><p>Just as we can overload functions, we can implement functions for Swift’s operators to achieve operator overloading. We can overload almost any operator. Swift only reserves a couple of operators to prevent changing fundamentals of the language. For instance, we can’t overload the assignment operator <em>=</em>.</p><p>Let’s overload the + operator so that it works as a union for NSSet.</p><pre>func <strong>+</strong>(lhs: NSSet, rhs: NSSet) -&gt; NSSet {<br>    return lhs.setByAddingObjectsFromSet(rhs)<br>}<br> <br>var x = NSSet(objects: &quot;a&quot;, &quot;b&quot;)<br>let y = NSSet(objects: &quot;b&quot;, &quot;c&quot;)<br>let z = NSSet(objects: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br>assert(x <strong>+</strong> y == z)</pre><p>While we’re at it, we overload the <em>+=</em> operator to match our new <em>+</em> operator:</p><pre>func <strong>+=</strong>(inout lhs: NSSet, rhs: NSSet) {<br>    lhs = lhs.setByAddingObjectsFromSet(rhs)<br>}<br> <br>x <strong>+=</strong> y<br>assert(x == z)</pre><p>Note that assignment operators defined in Swift don’t return the result of the assignment, to prevent errors like accidently typing <em>if x = y</em> instead of <em>if x == y</em> for Bool <em>x, y</em>. Our <em>+=</em> operator follows that lead.</p><h3>Examples</h3><p><strong>Being able to overload most of Swift’s operators is exciting; being able to define own operators even more so!</strong> On the other hand, an overloaded operator may be confusing; a new operator may be hard to type, and hard to understand. Let’s have a look at a couple of examples to better understand advantages and disadvantages.</p><h4>Examples: Operator Overloading</h4><p>Operators have certain traits we are used to. For example, from math we are used to addition working on values of the <em>same type</em>, being <em>associative</em>, meaning <em>(a + b) + c </em>is always <em>a + (b + c)</em>, and being <em>commutative</em>, meaning <em>a + b</em> is always <em>b + a</em>.</p><p>In C, the <em>+</em> operator mostly keeps these traits. The only exception I am aware of is pointer arithmetic, where values of different types (a pointer and an integer) are added. Still, the operation stays commutative and associative.</p><pre>int i = ...;<br>double *p = ...;<br> <br>double *p1 = p + i;<br>double *p2 = i + p;<br>assert(p1 == p2);</pre><p>Swift adds another exception: It defines a + operator for concatenating strings and arrays, which is not commutative:</p><pre>println(&quot;Hello&quot; + &quot;, &quot;+ &quot;World&quot;)<br>println([1, 2] + [3, 4])</pre><p>The Ruby programming language overloads the <em>*</em> operator, allowing to “multiply” an array with an integer, or a string. I think it’s only a matter of time before these appear in a third-party Swift module.</p><pre>let rects = [CGRectZero]<br>let result1 = <strong>rects * 3</strong><br> <br>let tags = [&quot;Swift&quot;, &quot;Custom&quot;, &quot;Operators&quot;]<br>let result2 = <strong>tags * &quot; &quot;</strong></pre><p>Is that good or bad code? If you don’t know Ruby, try to guess what <em>result1</em> and <em>result2</em> are, then check below for the answer.</p><pre>assert(result1 == <strong>[CGRectZero, CGRectZero, CGRectZero]</strong>)<br>assert(result2 == <strong>&quot;Swift Custom Operators&quot;</strong>)</pre><p>A last example of overloading I’d like to show you is from the <a href="https://github.com/indragiek/SwiftAutoLayout">SwiftAutoLayout</a> library. If you have ever created layout constraints in code, you may have noticed the code looks everything but pretty for simple constraints.</p><pre>let constraint = NSLayoutConstraint(item: view1, attribute: .Height, relatedBy: .Equal, toItem: view2, attribute: .Height, multiplier: 1.0, constant: 0.0)</pre><p>With the SwiftAutoLayout library, we can use operators to define constraints.</p><pre>let constraint = view1.al_height == view2.al_height</pre><p>It may be confusing at first that the “equal to” operator == returns an <em>NSLayoutConstraint</em> here instead of a <em>Bool</em>. As soon as we get used to that, the code using SwiftAutoLayout is much more readable.</p><h4>Examples: Custom Operators</h4><p>When we overload an existing operator, other programmers can guess the meaning of our operator from the original meaning. If we add a custom operator, we can borrow a meaning form another area like math, or logic.</p><p>That’s what we did when we added the logical operators. A much more complete version of that is <a href="https://github.com/mattt/Euler">Euler</a>, a library published by Mattt Thompson of <a href="http://nshipster.com">NSHipster</a> fame.</p><p>We could also borrow a meaning for our custom operator from another programming language. Then at least users of that language would feel right at home. For example, there is a comparison operator <em>&lt;=&gt;</em> in Ruby<em> </em>which we could define in Swift as well. Another example is the <a href="https://github.com/billylindeman/swiftgo">swiftgo</a> sample code, an incomplete implementation of goroutines in Swift that borrows Go’s <em>&lt;-</em> operator.</p><p>If there is no operator to be found, we can still make one up trying to convey the meaning we want by choosing an adequate symbol. That’s what we did with the swap operator &lt;-&gt;.</p><h3>Recommendations</h3><p>At the time of writing, Swift is still a young language, so take these recommendations with a grain of salt.</p><ul><li>We should never redefine predefined Swift behavior. Example: Don’t overload <em>+</em> on <em>[Int]</em> to make it an element-wise addition, as it clashes with the + on arrays which performs concatenation.</li><li>When overloading an operator, try to keep its general idea, its “spirit” alive. Example: SwiftAutoLayout’s overload of <em>==</em> returns a constraint which specifies two attributes have to be <em>equal to </em>each other. Even though <em>==</em> does not return a <em>Bool</em>, I think it’s OK, because <em>==</em> still stands for a kind of <em>equal to</em>.</li><li>If you overload an operator for which an assignment variant exists, overload the assignment variant as well if it makes sense. Example: Like shown with <em>+</em> and <em>+=</em> for <em>NSSet</em>.</li><li>If you think about adding an operator, think hard about the tradeoff brevity vs operator understanding. Example: Do <em>¬</em>, <em>∧</em>, and <em>∨</em> carry enough weight as alternatives to <em>!</em>, <em>&amp;&amp;</em>, and <em>||</em>?</li><li>If you add an operator, try to borrow a meaning from somewhere else. You can make up a new one as last resort, but then ask yourself why nobody else seemed to have the need for such an operator. Example: The swap operator <em>&lt;-&gt;</em>.</li><li>Most non-ASCII operators are hard to type. If you add non-ASCII operators in your project, make sure to add necessary text replacements via code snippets, or text expansion tools. We want to write code, not copy-paste it.</li></ul><p>Simply put in an overused, albeit fitting pop-culture reference: <strong>With great power comes great responsibility. </strong>Don’t let the list of recommendations discourage you though. Swift is a new language, have fun and experiment!</p><p>You’ve reached the end of this article, I hope you learned something new — I certainly learned lots writing it down.</p><p>I have one last topic that may not be important enough for all readers, but still may be of interest to some. As before, I put in the last section as a bonus track. Feel free to skip that section, but be back for the next article of this series, which will be about structures!</p><h3>Bonus Track: Boundaries of Operator Overloading</h3><p>As Swift allows us to overload operators, I wondered how many of Swift’s operators can actually be overloaded by us: Afew? The majority? Almost all?</p><p>We can’t overload a couple of operators because we don’t have the syntax for it: The ternary conditional <em>? : (</em>we can’t overload ternary operators), the cast operators <em>is</em>, <em>as</em>, and <em>as?</em> (we can’t use alphabetic characters in operators), the optional chaining operator ?, and the nil-coalescing operator <em>??</em> (we can’t use a question mark in operators).</p><p>In addition, we can’t overload three operators that are reserved by the compiler: the assignment <em>=</em>, the forced unwrapping postfix <em>!</em>, and the <em>&amp; </em>prefix used for in-out parameters.</p><p>So we can’t overload 9 operators.</p><pre>// ternary<br>? :<br>// infix<br>= is as as? ??<br>// prefix<br>&amp;<br>// postfix<br>? !</pre><p>But we can overload all remaining 46 operators:</p><pre>// infix<br>+ += - -= * *= / /= % %= &amp; &amp;= ^ ^= | |= &lt;&lt; &lt;&lt;= &gt;&gt; &gt;&gt;= &amp;+ &amp;- &amp;* &amp;/ &amp;% || &amp;&amp; &lt; &lt;= == != === !== &gt;= &gt; ..&lt; ... ~=<br>// prefix<br>-- ~ ! + — ++<br>// postfix<br>-- ++</pre><p>If we ignore the documentation and check Swift itself (1.0 in Xcode 6.0.1), we can overload two more operators: There is an undocumented infix operator ~&gt; in the Swift library, and the compiler currently allows us to overload ?? as well.</p><p>In summary: <strong>Swift allows us to overload all but the most fundamental operators.</strong></p><p>That’s all for today. Be back for the next article of this series, which will be about structures!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1080bc78ccc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/facets-of-swift-part-5-custom-operators-1080bc78ccc">Facets of Swift, Part 5: Custom Operators</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facets of Swift, Part 4: Functions]]></title>
            <link>https://medium.com/swift-programming/facets-of-swift-part-4-functions-3cce9d9bba4?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cce9d9bba4</guid>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Sun, 17 Aug 2014 21:03:31 GMT</pubDate>
            <atom:updated>2015-03-23T10:17:07.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Facets of Swift is a series of articles on various aspects of the Swift programming language. This fourth article is about functions. I wanted to cover methods as well, but it turned out that functions are such a broad topic they deserved an article of their own.</p><h3>Anatomy of a Function Declaration</h3><p>A function declaration in Swift has the following format:</p><pre>func functionName(parameters) -&gt; returnType {<br>    // statements<br>}</pre><p>To understand return types and parameters, it is helpful to know about tuples and tuple types in Swift. If you have read <a href="https://medium.com/swift-programming/facets-of-swift-part-2-tuples-4bfe58d21abf">the second article of this series</a> on tuples, great! You’re all set, and you can skip the next section. If you haven’t read the second article or you would like a refresher, just read on.</p><h3>Refresher: Tuples and Tuple Types</h3><p>Swift allows us to group two or more items in a tuple by putting the values in parentheses. We can access the elements of a tuple by their index:</p><pre>var result = <strong>(</strong>200, &quot;OK&quot;, true<strong>)</strong><br>println(result<strong>.1</strong>) // Prints &quot;OK&quot;</pre><p>We can optionally name some or all of the elements of the tuple. Named elements can be either accessed by index, or by their name:</p><pre>var result = (<strong>code:</strong> 200, <strong>name:</strong> &quot;OK&quot;, <strong>hasBody:</strong> true)<br>println(result<strong>.name</strong>) // Prints &quot;OK&quot;<br>println(result<strong>.1</strong>) // Prints &quot;OK&quot;</pre><p>Tuple types are built by putting two or more types in parentheses, optionally giving them names. That beautifully mirrors how tuples are defined. When assigning tuples, the types of the elements must match. Furthermore, when names are given, the names must match:</p><pre>var result: (<strong>code:</strong> Int, String)<br>result = (<strong>code:</strong> 200, “OK”)       // OK (no name mismatches)<br>result = (200, <strong>name:</strong> “OK”)       // OK (no name mismatches)<br>result = (200, “OK”)             // OK (no name mismatches)<br>result = (<strong>statusCode:</strong> 200, “OK”) // COMPILER ERROR (name mismatch)</pre><p>There is also a tuple with no elements, the empty tuple with the empty tuple type.</p><pre>var empty: <strong>()</strong> = <strong>()</strong></pre><p>In the previous example, we declared the type explicitly as the compiler warns if the empty tuple type is inferred. The type <em>Void</em> is a type alias for the empty tuple type <em>()</em>:</p><pre>var empty: <strong>Void</strong> = ()</pre><p>For single values and types, parentheses are used to group expressions only: <em>T</em>, <em>(T)</em>, <em>((T))</em>, and so on all refer to the same type. In the following code snippet, <em>foo</em> has type <em>Int</em>:</p><pre>let foo: ((Int)) = ((42))</pre><p>Of course, the parentheses are not needed and the type can be inferred, so we can write shorter code instead:</p><pre>let foo = 42</pre><h3>Return Types</h3><p>After a short recap of what tuples are, we can compare the various possible return types in Swift. The return value of a function can be any single type, or any tuple type.</p><h4>Returning Nothing</h4><p>We can declare that a function returns nothing by using the empty tuple type:</p><pre>func foo() <strong>-&gt; ()</strong> {<br>}</pre><p>If we prefer, we can write <em>Void</em> instead of <em>()</em>:</p><pre>func foo() <strong>-&gt; Void</strong> {<br>}</pre><p>The empty tuple type is the default return type for functions, so we can omit it to improve readability:</p><pre>func foo() {<br>}</pre><p>Having <em>Void</em> as default return type for a function is a better choice than in C, where the default return value is <em>int</em>:</p><pre>foo() {<br>    return 42;<br>}</pre><p>Why is that a better choice? Specifying nothing as a return type means that you get the closest thing to nothing there is in Swift, and not a number.</p><h4>A Single Return Type</h4><p>We can declare that a function has a single return type:</p><pre>func foo() <strong>-&gt; Int</strong> {<br>    return 42<br>}</pre><p>I assume most of the Swift code we write will use either no return type, or a single return type. In C and Objective-C, we only have those two choices. The designers of Swift however decided to allow more.</p><h4>Two or More Return Types</h4><p>In Swift, we can use tuples to return more than one element from a function. We use the tuple type as return type, and return a tuple:</p><pre>func okStatus() -&gt; <strong>(code: Int, name: String, hasBody: Bool)</strong> {<br>    return <strong>(200, &quot;OK&quot;, true)</strong><br>}<br>let status = okStatus()<br>println(status.name) // Prints &quot;OK&quot;</pre><p>To summarize: <strong>In Swift, a function’s return type is the empty tuple type by default. We can also use a single type, or a tuple type with two or more (optionally named) elements as return type.</strong></p><p>Now that we know about return types, let’s have a look at parameters.</p><h3>Parameters</h3><p>Parameters offer even more possibilities than the return type. First, we’ll have a look at the parameter list itself. Then, we cover the three kinds of parameter passing, followed by explaining three special parameter kinds.</p><h4>No Parameters</h4><p>We can specify an empty parameter list by leaving the space between the parentheses empty. No surprises here:</p><pre>func foo<strong>()</strong> {<br>}<br>foo<strong>(42)</strong> // COMPILER ERROR</pre><p>That’s different in C, where empty parentheses are interpreted as an unspecified number of parameters:</p><pre>void foo<strong>()</strong> {<br>}<br>foo<strong>(42)</strong> // NO COMPILER ERROR</pre><p>Parameters for Objective-C blocks are handled in the same manner. The following code snippet compiles without errors:</p><pre>void (^block)<strong>()</strong>;<br>block = ^(int i) {<br>    printf(&quot;%d\n&quot;, i);<br>};<br> <br>block<strong>()</strong>;<br>block<strong>(1)</strong>;<br>block<strong>([NSObject new], 42)</strong>;</pre><p>To state that we don’t want to allow parameters to be passed in C or Objective-C, we need to put <em>void</em> between the parentheses:</p><pre>void foo(<strong>void</strong>) {<br>}<br>// ...<br>foo<strong>(42)</strong>; // COMPILER ERROR</pre><p>As with the return type, Swift has a better default behavior than C/Objective-C: Specifying no parameters means having no parameters, and not any number of parameters. But of course, functions that actually accept parameters are way more interesting.</p><h4>One or More Parameters</h4><p>To accept one or more parameters, just put the names and types between the parentheses of the function declaration, and the values between the parentheses of the function call:</p><pre>func foo(<strong>x: Int, y: Int, z: Int</strong>) {<br>}<br>foo(<strong>1, 2, 3</strong>)</pre><p>Now that looks very similar to what we’re used to from C.</p><h4>Parameter Passing</h4><p>As mentioned <a href="https://medium.com/swift-programming/facets-of-swift-part-3-values-and-references-d2aac239d6f4">in the previous article</a>, by default a parameter in Swift is passed as a constant. That means its value can’t be changed inside the body of a function:</p><pre>func foo(i: Int) {<br>    i++ // COMPILER ERROR<br>}</pre><p>If we want to, we can explicitly state that a parameter is a constant:</p><pre>func foo(<strong>let</strong> i: Int) {<br>    i++ // COMPILER ERROR<br>}</pre><p>By defining the parameter as a variable, we can change it inside the function body:</p><pre>func foo(<strong>var</strong> i: Int) {<br>    i++<br>}</pre><p>The changes won’t make it out of the function, though. If we would like to change the variable with which the function is called, we declare the parameter as an in-out parameter using the keyword <em>inout</em>. Then at the caller side, we have to pass in a variable which is prefixed with an ampersand:</p><pre>func foo(<strong>inout i: Int</strong>) {<br>    i++<br>}<br>var x = 1<br>foo(<strong>&amp;x</strong>)<br>println(x)</pre><p>So we have three kinds of parameter passing. There are three kinds of special parameters as well.</p><h4>Special Kinds of Parameters</h4><p>The first special type is the ignored parameter. If we don’t want to use the value inside the function, but still require it as a parameter, we can use an underscore instead of a variable name:</p><pre>func foo(<strong>_: Int</strong>) {<br>}<br>foo(42) // OK<br>foo() // COMPILER ERROR</pre><p>An ignored parameter frees us of having to come up with a name for a parameter we don’t use, like when we override a method and don’t use a given parameter, or implement a closure and don’t use a given parameter. Both cases will be covered in detail in later articles.</p><p>For plain functions, I don’t see much use for an ignored parameter. That’s quite different for the second special kind of parameters: By using the type <em>T…</em>, we can make a function accept a variable number of values of type <em>T</em>. Inside the function, the parameter is exposed as an array with type <em>[T]</em>. The following code will print the numbers from 1 to 4, each on a separate line:</p><pre>func printNumbers(numbers: <strong>Int...</strong>) {<br>    for number in numbers {<br>        println(number)<br>    }<br>}<br>printNumbers<strong>(1)</strong><br>printNumbers<strong>()</strong><br>printNumbers<strong>(2, 3, 4)</strong></pre><p>Such a parameter is called a <em>variadic parameter</em>. You may know variadic parameters from C and Objective-C, but maybe you never built a function with a variadic parameter because accessing the values was a bit of a pain. In Swift, a variadic parameter is very easy to use. I think we will see more of those.</p><p>The variadic parameter comes with a few strings attached. We may only use one per function. While that may seem as an unnecessary restriction, it prevents ambiguity and general code horror. The variadic parameter has to be the last in the list—a good design decision as it would feel really weird to have an optional number of parameters at the beginning, or in between other parameters. We can’t use <em>inout</em> on a variadic parameter: If we need to modify a list of values from our function, we can use an in-out array parameter instead. The documentation says nothing about using <em>var</em> on a variadic parameter, so we better avoid it. Besides, the current beta 5 compiler crashes if we try.</p><p>The third kind of special parameter is the parameter with default value. Imagine we write a helper function that prints a separator. This could be how the function looks like:</p><pre>func printSeparator() {<br>    // ...<br>}</pre><p>Two problems here. First, while the function name suggests that a separator is printed, there is no hint on how the separator looks. Second, we could not change the look of the separator. Default parameters to the rescue:</p><pre>func printSeparator(<strong>separatorCharacter: String = &quot;-&quot;, count: Int = 79</strong>) {<br>    // ...<br>}</pre><p>Much better. Now the code suggests that the methods by default prints the “<em>-</em>” character 79 times. We also have the possibility to change those defaults:</p><pre>printSeparator() <strong>          </strong>                  <strong>      </strong> // (1)<br>printSeparator(<strong>separatorCharacter:</strong> &quot;=&quot;)      <strong>      </strong>// (2)<br>printSeparator(<strong>count:</strong> 50)                            // (3)<br>printSeparator(<strong>separatorCharacter:</strong> &quot;=&quot;, <strong>count:</strong> 50) // (4)<br>printSeparator(<strong>count:</strong> 50, <strong>separatorCharacter:</strong> &quot;=&quot;) // (5)</pre><p>We would now expect that (1) prints “-” 79 times, (2) prints “=” 79 times, (3) prints “-” 50 times, both (4) and (5) print “=” 50 times. Things to note here are that we can skip default parameters from the beginning and only override later defaults (3), and that we are free to order the defaults however we want (4), (5). The most obvious difference is: <strong>Required function parameters in Swift are unnamed by default, parameters with default values are named by default.</strong> We have to pass the arguments by name, the following code would not compile:</p><pre>printSeparator(&quot;=&quot;)     // COMPILER ERROR<br>printSeparator(&quot;=&quot;, 50) // COMPILER ERROR</pre><p>The term “parameter with default <em>value</em>”<em> </em>is misleading. Both the Swift grammar, and the compiler allow a default <em>expression</em>:</p><pre>func foo(number: UInt32 = arc4random()) {<br>    println(number)<br>}<br>foo() // Prints a random number</pre><h4>Parameter Order</h4><p>We can put parameters with default values in front of parameters without default values:</p><pre>func foo(<strong>a: Int = 0, b: Int) </strong>{<br>}<br>foo(2)<br>foo(a: 1, 2)</pre><p>Try to avoid such code though, it’s hard to read. Better put required parameters first, followed by parameters with default values:</p><pre>func foo(<strong>b: Int, a: Int = 0) </strong>{<br>}<br>foo(2)<br>foo(2, a: 1)</pre><h3>Parameter Names</h3><p>We’ve seen that Swift has named and unnamed parameters. That’s not the whole story though. Each parameter in Swift has an <em>external name </em>and a <em>local name</em>. The external name is used when calling the function, the local name is used inside the function. In the following code snippet <em>latitude </em>is the external name, and <em>lat </em>the local name:</p><pre>func foo(<strong>latitude lat</strong>: Float) {<br>    // ...<br>}<br>foo(<strong>latitude: </strong>53.48)</pre><p>If we don’t want to use an external name, we use an underscore instead; if we don’t want to use a local name, we use an underscore instead (which gives us an ignored parameter).</p><p>It would be quite annoying though if we would have to always write down external and local parameter. The Swift designers put defaults in place that help us to write shorter code. Whenever we miss an opportunity to write shorter code, the compiler warns us that our code is too long.</p><h4>Naming Required Parameters</h4><p>Coming from C, we are used to function parameters without external names. A plain function parameter in Swift does not have an external name by default as well. So instead of</p><pre>func foo(<strong>_ lat: Float</strong>) {  // COMPILER WARNING<br>    // ...<br>} <br>foo(53.48)</pre><p>we can write</p><pre>func foo(<strong>lat: Float</strong>) {<br>    // ...<br>}<br>foo(53.48)</pre><p>If we like, we have the option to use an external name:</p><pre>func foo(<strong>latitude lat</strong>: Float) {<br>    // ...<br>}<br>foo(latitude: 53.48)</pre><p>If the external and internal name are the same, the compiler warns us that there is a shorter alternative:</p><pre>func foo(<strong>lat lat: Float) </strong>{  // COMPILER WARNING<br>     // ...<br>}<br>foo(lat: 53.48)</pre><p>The shorter alternative is to put a hash symbol in front of the parameter name:</p><pre>func foo(<strong>#lat: Float) </strong>{<br>     // ...<br>}<br>foo(lat: 53.48)</pre><h4>Naming Parameters With Default Values</h4><p>For a parameter with a default value, the default behavior is to use the same external and local name. So instead of</p><pre>func foo(<strong>#lat: Float = 0.0</strong>) {  // COMPILER WARNING<br>    // ...<br>}<br>foo(lat: 53.48)</pre><p>we can write</p><pre>func foo(<strong>lat: Float = 0.0</strong>) {<br>    // ...<br>}<br>foo(lat<strong>:</strong> 53.48)</pre><p>It is a good idea to name parameters with default values. If a function has more that one parameter with a default value, the names allow us to only change those parameters we want:</p><pre>func foo(<strong>lat: Float = 0.0, lng: Float = 0.0</strong>) {<br>     // ...<br>}<br>foo(lat<strong>:</strong> 53.48)<br>foo(lng<strong>:</strong> 9.95)</pre><p>We can still get an externally unnamed parameter with default value by using an underscore as external name:</p><pre>func foo(<strong>_ lat: Float = 0.0</strong>) {<br>    println(&quot;Latitude: \(lat)&quot;)<br>}<br>foo(53.48)</pre><p>Parameters with default values are a great way to keep compatibility when improving an existing API. We can add a new parameter with a default value.</p><pre>// Before<br>func foo() {<br>    // ...<br>}<br>// After<br>func foo(<strong>x: Int = 0</strong>) {<br>    // ...<br>}</pre><p>Old code still compiles without errors; new code can use the parameter to set another value than the default. Or we can add a default value to a preexisting parameter. Again, old code still compiles without errors, new code can call the function without the parameter.</p><pre>// Before<br>func foo(<strong>x: Int</strong>) {<br>    // ...<br>}<br>// After<br>func foo(_ <strong>x: Int = 0.0</strong>) {<br>    // ...<br>}</pre><h4>Ignored Parameters</h4><p>To ignore a parameter, we use the underscore as local name:</p><pre>func foo(<strong>lat _: Float</strong>) {<br>}<br>foo(lat<strong>:</strong> 53.48)</pre><p>If we don’t want to use an external name, we use an underscore as well:</p><pre>func foo(<strong>_ _: Float</strong>) {  // COMPILER WARNING<br>}<br>foo(53.48)</pre><p>The compiler warns us as there is a shorter alternative:</p><pre>func foo(<strong>_: Float</strong>) {<br>}<br>foo(53.48)</pre><h4>Naming Parameters: Recommendation</h4><p>When naming function parameters, we have lots of freedoms. Deviating from the defaults however can make our code harder to understand. Therefore we should try to use the default as much as possible.</p><h3>Function Types</h3><p>In C, we have function pointers which we can use to reference functions:</p><pre>int sum(int a, int b) {<br>    return a + b;<br>}<br>// ...<br><strong>int (*foo)(int, int)</strong> = sum;<br>printf(&quot;%d\n&quot;, foo(1, 2));</pre><p>The variable <em>foo</em> has a function pointer type mapping two <em>int</em> parameters to an <em>int</em> return value. In Objective-C, we have block variables which we can use to reference blocks:</p><pre><strong>int (^foo)(int, int)</strong> = ^(int a, int b) {<br>    return a + b;<br>};<br>printf(&quot;%d\n&quot;, foo(1, 2));</pre><p>The variable <em>foo</em> has a block pointer type mapping two <em>int</em> parameters to an <em>int</em> return value. In Swift, we have function types as well:</p><pre>func sum(a: Int, b: Int) -&gt; Int {<br>    return a + b<br>}<br>var foo: (Int, Int) -&gt; Int = sum<br>println(foo(1, 2))</pre><p>The variable <em>foo </em>has a function type mapping two <em>Int </em>parameters to an <em>Int </em>return value, or more exact mapping a tuple of type <em>(Int, Int)</em> to the type <em>Int</em>.</p><h4>So Pretty</h4><p>Swift’s function types are a huge improvement over C and Objective-C. It’s immediately obvious that they are way more readable. Imagine you want a variable <em>foo</em> with a function type that maps a function from <em>Int</em> to <em>Int</em> to a function from <em>Int</em> to <em>Int</em>. That’s both easy to write down in the first try, and easy to read:</p><pre>var foo: (Int -&gt; Int) -&gt; (Int -&gt; Int)</pre><p>In C, the same variable would look like this:</p><pre>int (*(*foo)(int (*)(int)))(int);</pre><p>While some of us may write this down correctly in the first try, reading it is always painful. Granted, we could improve things a bit with a <em>typedef</em>, but even then the C code is less readable than the Swift version:</p><pre>typedef int (*IntToInt)(int);<br>IntToInt (*foo)(IntToInt);</pre><p>Swift’s function types also unify functions and closures (pieces of code without a name comparable to Objective-C blocks): Both have function types, so a variable with a function type can either reference a function or a closure. In contrast, Objective-C’s blocks are different to C’s function pointers. Closures will be covered in a later article.</p><h4>Type Inference</h4><p>If the type of the function can be inferred from the function, we don’t need to write the type of a function down:</p><pre>func sum(a: Int, b: Int) -&gt; Int {<br>    return a + b<br>}<br><strong>var foo = sum</strong><br>println(foo(1, 2))</pre><p>The type can’t be inferred if the function is overloaded or uses generics. Then we have to write down the function type to specify which function we want. Here is an example where we get a <em>lessThan</em> function for <em>Int</em> parameters from the <em>&lt;</em> operator:</p><pre>let lessThan: <strong>(Int, Int) -&gt; Bool</strong> = (&lt;)<br>println(lessThan(1, 2)) // prints &quot;true&quot;</pre><p>The parentheses around the <em>&lt;</em> symbol are needed to make the compiler happy.</p><p>Function overloading, generics, and operators will be covered in later articles.</p><h4>Void: Less Special Than in C</h4><p>In C, there is no value for the type <em>void</em>, so you can’t declare a variable of <em>void</em> type:</p><pre>void foo(void) {<br>}<br>// ...<br>void x = foo(); // COMPILER ERROR</pre><p>Swift’s <em>Void</em> is less special than C’s <em>void</em>. It is a type alias for the empty tuple type <em>().</em> So there is exactly one value for it, the empty tuple <em>()</em>. Because there is a value for the <em>Void</em> type, all functions in Swift have a return value! A function with return type <em>Void</em> simply returns the empty tuple:</p><pre>func foo() {<br>}<br>var result: Void = foo()</pre><p>The code even works without the type declaration on the variable <em>result</em>. The compiler only warns us we may not have intended to infer the empty tuple type:</p><pre>func foo() {<br>}<br>var result = foo()  // COMPILER WARNING</pre><p>We can even return the empty tuple from our function:</p><pre>func foo() {<br>    return ()<br>}</pre><p>An empty parameter list in Swift behaves just the same. A function <em>foo()</em> can be called with the empty tuple as parameter:</p><pre>func foo() {<br>}<br>foo(<strong>()</strong>)</pre><p>What we should remember is: <strong>For Swift functions, <em>Void</em> is less special than in C: It is just a type with one valid value.</strong></p><h3>Function Types and Tuples</h3><p>If you have read the bonus track of the <a href="https://medium.com/swift-programming/facets-of-swift-part-2-tuples-4bfe58d21abf">second article of this series</a>, you may remember that while Apple’s Swift book states that <em>(Int)</em> is <em>Int</em>, the other way round seems to be more accurate: All types behave like they are a 1-tuple. For example, the following code works just fine:</p><pre>let x = 42<br>println(x<strong>.0</strong>)</pre><p>We can also write down a named 1-tuple:</p><pre>let x: (y: Int)  = 42<br>println(x.y)</pre><p>That is wonderful because together with the handling of <em>Void</em>, it simplifies function types a lot. <strong>If we read a type <em>T</em> as 1-tuple <em>(T)</em> and ignore special parameter types, all functions in Swift map from an input tuple type to an output tuple type</strong>. No more special cases. Beautiful.</p><p>Of course, as Swift is a language still in beta, there are a couple of unexpected behaviors which are not that beautiful. As they may be confusing (and outdated pretty soon), I moved them to the last section as a bonus track. Feel free to skip that section, but be back for the next article of this series about methods!</p><h3>Bonus Track: Parameter Misbehavior</h3><p>There are two areas where the current (beta 5) Swift feels a bit weird: Handling of tuples as arguments, and special parameter types.</p><h4>Tuples as Arguments</h4><p>While a function’s parameters feel like a tuple type, the compiler sometimes needs to be convinced to accept a tuple. Here is some code I would expect to compile:</p><pre>func foo(#a: Int) {}<br> <br>let arg1 = <strong>(a: 42)</strong><br>var arg2 = <strong>(a: 42)</strong><br> <br>foo(<strong>(a: 42)</strong>)    // COMPILER ERROR<br>foo(arg1)<strong>       </strong>// COMPILER ERROR<br>foo(arg2)<strong>       </strong>// COMPILER ERROR</pre><p>We get compiler errors as Swift currently seems to not infer named 1-tuples. If we set a breakpoint, we see that <em>arg1</em> and <em>arg2</em> are of type <em>Int</em>, not <em>(a: Int)</em>. Let’s try to help the compiler a bit:</p><pre>func foo(#a: Int) {}<br> <br>let arg1<strong>: (a: Int)</strong> = (a: 42)<br>var arg2<strong>: (a: Int)</strong> = (a: 42)<br> <br>foo((a: 42) <strong>as (a: Int)</strong>)<br>foo(arg1)<br>foo(arg2) // COMPILER ERROR</pre><p>This compiles, except for the last line. Although the variable <em>arg2</em> has the correct type, it is still not accepted by the compiler, while the constant <em>arg1</em> is! To get the code to compile, we have to add yet another cast:</p><pre>...<br>foo(arg2 <strong>as (a: Int)</strong>)</pre><p>In the future, Swift may change so that the casts are not needed anymore. The example illustrates an important point: <strong>Swift needs a named 1-tuple to represent the parameter type of a function with one named parameter.</strong> Here, the function type of <em>foo</em> is <em>(a: Int) -&gt; ()</em>.</p><p>The current compiler also gives us a bit of a hard time when using tuples with two or more elements as arguments. Here is an example I would expect to compile:</p><pre>func foo1(a: Int, b: Int) {}<br>func foo2(a: (Int, Int)) {}<br> <br>var arg1 = (42, 42)<br>var arg2 = 42<br> <br>foo1(<strong>arg1</strong>)<strong>    </strong>      // COMPILER ERROR<br>foo1(<strong>arg2, arg2</strong>)<br>foo1(<strong>42, 42</strong>)<br>foo1(<strong>(42, 42)</strong>)      // COMPILER ERROR<br> <br>foo2(<strong>arg1</strong>)<br>foo2(<strong>arg2, arg2</strong>)    // COMPILER ERROR<br>foo2(<strong>42, 42</strong>)<strong>    </strong>    // COMPILER ERROR<br>foo2(<strong>(42, 42)</strong>)</pre><p>Why should all this work? Well, both <em>foo1</em> and <em>foo2</em> have the same function type <em>(Int, Int) -&gt; ()</em>. Again, we get a couple of errors. Again, we can fix the code by adding casts:</p><pre>func foo1(a: Int, b: Int) {}<br>func foo2(a: (Int, Int)) {}<br> <br>var arg1 = (42, 42)<br>var arg2 = 42<br> <br>foo1(arg1<strong> as (Int, Int)</strong>)<br>foo1(arg2, arg2)<br>foo1(42, 42)<br>foo1((42, 42)<strong> as (Int, Int)</strong>)<br> <br>foo2(arg1)<br>foo2(arg2<strong> as Int</strong>, arg2<strong> as Int</strong>)<br>foo2(42<strong> as Int</strong>, 42<strong> as Int</strong>)<br>foo2((42, 42))</pre><p>Let’s hope that gets cleaned up before Swift 1.0!</p><h4>Tuples and Special Parameter Types</h4><p>A function type maps from an input type (parameter type) to an output type (return type). There are three special types of parameters: in-out parameters, variadic parameters, and parameters with default values. The current Swift beta 5 compiler does not handle them that well.</p><p>If we define a function with an in-out parameter and check its type in the debugger, we see an attribute <em>@lvalue</em> on the inout parameter type. For the variable <em>bar</em> in the following code snippet, the debugger reports a type of (<em>@lvalue Int, Int) -&gt; ()</em>:</p><pre>func foo(inout a: Int, b: Int) {}<br>var bar = foo</pre><p>However, currently we can’t use <em>@lvalue</em> in our code to build a tuple we could use to call <em>foo</em> or <em>bar</em> with, nor is it a type we can write down. If we want to call the function with a tuple, we have to split the arguments manually:</p><pre>func foo(inout a: Int, b: Int) {<br>}<br> <br>var arg = (42, 42)<br>foo(<strong>&amp;arg.0, arg.1</strong>)</pre><p>For variadic parameters, the beta 5 debugger reports them wrongly as the empty tuple type. For the variable <em>bar </em>in the following code snippet, the debugger reports a type of <em>() -&gt; ()</em>:</p><pre>func foo(a: Int...) {}<br>var bar = foo</pre><p>That’s obviously wrong, as the function accepts any number of <em>Int</em> arguments.</p><p>Parameters with default values simply disappear in the reported function type, as if there were no defaults. For the variable <em>bar </em>in the following code snippet, the debugger reports a type of <em>(Int, b: Int) -&gt; ()</em>:</p><pre>func foo(a: Int, b: Int = 42) {}<br>var bar = foo</pre><p>Maybe this is by intention and <em>bar</em> should only be callable with both parameters? The compiler does not gives us a good hint: <em>bar(1)</em> is neither compiled successfully nor with an error, but it crashes the compiler. Maybe the next Swift version gives us a better hint what’s expected. Whatever happens to bar, there is no way to completely express the function type of <em>foo</em>, as there is no way of writing down a tuple type with defaults.</p><p>These rough edges should not discourage us, though. Swift’s function and function types are already way more impressive than what we have in C and Objective-C.</p><p>There are lots of interesting topics on functions still to cover, but this article already got way too long. I’ll write about those in future articles. Be back for the next article of this series, which will cover methods!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cce9d9bba4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/facets-of-swift-part-4-functions-3cce9d9bba4">Facets of Swift, Part 4: Functions</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facets of Swift, Part 3: Values and References]]></title>
            <link>https://medium.com/swift-programming/facets-of-swift-part-3-values-and-references-d2aac239d6f4?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2aac239d6f4</guid>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Mon, 21 Jul 2014 14:46:49 GMT</pubDate>
            <atom:updated>2014-10-05T20:11:04.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Facets of Swift is a series of articles on various aspects of the Swift programming language. This third article is about values and references in Swift. Originally I had planned to write about functions. I chose to write about values and references first as there are a few gotchas related to values in Swift that confuse even seasoned Objective-C developers.</p><h3>Pass by Value</h3><p>In C and Objective-C, values are passed everywhere, not references. What does the following code snippet do?</p><pre>void foo(int i) {<br>    <strong>i++</strong>;<br>}<br>// ...<br>int <strong>x = 1</strong>;<br><strong>foo(x)</strong>;<br><strong>printf</strong>(&quot;%d\n&quot;, <strong>x</strong>);</pre><p>It will print “<em>1</em>”, as <em>foo</em> gets passed the value<em> </em>of <em>x</em> in the parameter <em>i</em>. So <em>foo</em> has no way of changing what’s stored in the variable <em>x</em>. When we try to convert the code directly to Swift, we stumble over a compiler error:</p><pre>func foo(i: Int) {<br>    <strong>i++</strong> // COMPILER ERROR<br>}<br>// ...<br>var x = 1<br>foo(x)<br>println(x)</pre><p><strong>In Swift, function parameters are constant by default.</strong> The function declaration above is shorthand for</p><pre>func foo(<strong>let</strong> i: Int) {<br>    i++ // COMPILER ERROR<br>}</pre><p>It’s a good thing that the default changed that way: In C, especially beginners could be fooled too easily into thinking that the first example would return “<em>2</em>”, not “<em>1</em>”.</p><p>If we want to modify the value of <em>i</em> in the function body in Swift, we can define <em>i</em> as a variable:</p><pre>func foo(<strong>var</strong> i: Int) {<br>    <strong>i++</strong><br>}<br>// ...<br>var x = 1<br>foo(x)<br>println(x)</pre><p>Keep in mind that this still does not allow us to modify the value of the variable <em>x</em> that was passed in. Just as the C version, the code would now print “1”. What if we would like to change the value of the variable <em>x</em>?</p><h3>Pass by Reference</h3><p>In C, we would pass a pointer instead:</p><pre>void foo(int <strong>*</strong>i) {<br>    <strong>(*i)</strong>++;<br>}<br>// ...<br>int x = 1;<br>foo(<strong>&amp;x</strong>);<br>printf(&quot;%d\n&quot;, x);</pre><p>Now <em>foo</em> gets passed the address <em>&amp;x</em> (a reference to <em>x</em>), and can dereference that address using <em>(*i)</em> to change the value. The code will now print “<em>2</em>”. Keep in mind that from a technical perspective, this is still a pass by value: We pass the pointer as value.</p><p>In Swift, we use the keyword <em>inout</em> to tell the compiler that the variable is an in-out parameter:</p><pre>func foo(<strong>inout</strong> i: Int) {<br>    <strong>i++</strong><br>}<br>// ...<br>var x = 1<br>foo(<strong>&amp;x</strong>)<br>println(x)</pre><p>Compared to the C code, the Swift version looks a bit cleaner: While we still have to use <em>&amp;</em> to pass a variable as an in-out parameter, we don’t need to dereference the parameter <em>i</em> to change the value. Inside the function, <em>i</em> feels like a variable, not a pointer.</p><p><strong>In Swift, we use nothing or <em>let</em> to make a parameter constant, <em>var</em> to make it variable, and <em>inout</em> to make it an in-out parameter.</strong></p><h3>Constant Parameters in C</h3><p>So the default in Swift is to have constant parameters. Can we have those in C as well? We can. But as it’s C, the story is a bit more complicated. Let’s start with this example:</p><pre>void foo(CGSize s) {<br>    NSLog(@&quot;%@&quot;, NSStringFromCGSize(s));<br>}<br>// ...<br>CGSize size = {1, 1};<br>foo(size);</pre><p>It will print “<em>{1, 1}</em>”. Imagine <em>CGSize</em> would be a big structure, so we want to be able to pass it to <em>foo</em> via a pointer, but without worrying about <em>foo</em> changing it. We can achieve that by using <em>const</em>:</p><pre>void foo(CGSize <strong>const *</strong>s) {<br>    NSLog(@&quot;%@&quot;, NSStringFromCGSize(<strong>*</strong>s));<br>}<br>// ...<br>CGSize size = {1, 1};<br>foo(<strong>&amp;</strong>size);</pre><p>If we try to modify what <em>s</em> points to, we get a compiler error:</p><pre>void foo(CGSize <strong>const *</strong>s) {<br>    (*s).width = 0 // COMPILER ERROR<br>}</pre><p>The placement of <em>const</em> is crucial here. If we write <em>const</em> after the pointer, the code would compile:</p><pre>void foo(CGSize <strong>*const </strong>s) {<br>    (*s).width = 0<br>}</pre><p>To understand what’s going on, it helps to start reading from the variable name backwards. Still, covering all cases is quite a long list:</p><ul><li><strong><em>CGSize s</em></strong>: <em>s</em> is a <em>CGSize</em> (which can be modified in the function). This is comparable to <em>var s: CGSize</em> in Swift.</li><li><strong><em>CGSize const s</em></strong>: <em>s </em>is a <em>const</em> <em>CGSize</em>, so it can’t be modified in the function. This is comparable to <em>s: CGSize</em> or <em>let s: CGSize</em> in Swift.</li><li><strong><em>CGSize *s</em></strong>: <em>s</em> is a pointer to a <em>CGSize</em>, so both the pointer <em>s</em> and the <em>CGSize</em> structure pointed to can be modified inside the function.</li><li><strong><em>CGSize *const s</em></strong>: <em>s</em> is a <em>const</em> pointer to a <em>CGSize</em>, so the pointer <em>s</em> can’t be modified inside the function, the <em>CGSize</em> structure pointed to can. This is roughly comparable to <em>inout s: CGSize </em>in Swift, as Swift hides the pointer from us, so we can’t modify it, but we can modify the value pointed to.</li><li><strong><em>CGSize const *s</em></strong>: <em>s</em> is a pointer to a <em>const</em> <em>CGSize</em>, so the pointer <em>s</em> can be modified, the <em>CGSize</em> structure pointed to can’t.</li><li><strong><em>CGSize const *const s</em></strong>: <em>s</em> is a <em>const</em> pointer to a <em>const CGSize</em>, so both the pointer <em>s</em> and the <em>CGSize</em> structure pointed to can’t be modified.</li></ul><p>If you wondered about it, in all cases above we could replace <em>CGSize const</em> with its equivalent <em>const CGSize</em>.</p><p>We identified six cases, for three of which we don’t have a comparable construct in Swift. And that’s great:</p><ul><li><strong><em>CGSize *s</em></strong> would force us to expose the pointer that Swift hides so well.</li><li><strong><em>CGSize const *s</em></strong> and <strong><em>CGSize const *const s</em></strong> can be used for performace optimizations in C: Instead of passing a copy of the struct’s value, we pass a pointer that does not allow the modification of the content. In Swift, we leave that optimization to the compiler, instead of polluting our code with it.</li></ul><p>Now that we covered how constants work for structures and pointers, let’s have a look at what’s different for objects.</p><h3>Objects</h3><p>In Objective-C, we mostly work with objects which are subclasses of <em>NSObject. </em>Whenever we pass an object, or store it in a variable, we reference it using a pointer:</p><pre>void foo(NSMutableString *s) {<br>}<br>// …<br>NSMutableString *string = [NSMutableString new];<br>foo(string);<br>NSLog(@”%@”, string);</pre><p>An object variable should be able to hold an object of the respective class, or any subclass of it. Objects of different classes can have different sizes, so we can’t know the size. Therefore the compiler does not allow us to store the structure of an object in a variable directly, we have to use a pointer:</p><pre>NSObject object1; // COMPILER ERROR<br>NSObject *object2; // OK</pre><p>More importantly, we can’t use <em>const </em>to prevent changes to an object:</p><pre>void foo(<strong>NSMutableString const *</strong>s) {<br>    [s appendString:@&quot;OH NOES&quot;]; // No compiler error here!<br>}<br>// ...<br>NSMutableString *string = [NSMutableString new];<br>foo(string);<br>NSLog(@&quot;%@&quot;, string); // Prints &quot;OH NOES&quot;</pre><p>We can make the pointer a constant, but as we’ve seen above for structures, that does not prevent us from changing the object pointed to, only from changing the pointer:</p><pre>void foo(<strong>NSMutableString *const</strong> s) {<br> [s appendString:@&quot;OH NOES&quot;];<br>}<br>// …<br>NSMutableString *string = [NSMutableString new];<br>foo(string);<br>NSLog(@&quot;%@&quot;, string); // Prints &quot;OH NOES&quot;</pre><p>In Swift, classes are reference types by default, so there is no need to write pointers:</p><pre>func foo(<strong>s: NSMutableString</strong>) {<br>    s.appendString(“OH NOES”)<br>}<br>// ...<br>var string = NSMutableString()<br>foo(string)<br>println(string) // Prints &quot;OH NOES&quot;</pre><p>Swift has the additional advantage that <em>s</em> is required to be non-<em>nil </em>(for details, see <a href="https://medium.com/swift-programming/facets-of-swift-part-1-optionals-b8ba5b0051a2">the first <em>Facets of Swift</em> article on optionals</a>). The three cases for parameters in Swift cover all we need for objects:</p><ul><li><strong><em>s: NSObject?</em></strong> is comparable to <em>NSObject *const s</em> in Objective-C. If we would like the parameter to be non-<em>nil</em>, we would use <strong><em>s: NSObject</em></strong><em>.</em></li><li><strong><em>var s: NSObject?</em></strong> is comparable to <em>NSObject *s</em> in Objective-C. If we would like the parameter to be non-<em>nil</em>, we would use <strong><em>var s: NSObject.</em></strong></li><li><strong><em>inout s: NSObject?</em></strong> is comparable to <em>NSObject **s</em>, which is the short form of <em>NSObject * __autoreleasing *s</em> in Objective-C.</li></ul><p>The last case shows how much cruft is removed in Swift. Bottom line: <strong>In Swift, objects are automatically passed by reference, which leads to better readable code, especially for inout parameters.</strong></p><h3>Gotcha: Focus on Values</h3><p>When we look at Objective-C code, it almost always defines classes. For example, strings, arrays and dictionaries are objects of classes. That means that whenever we pass an object around in Objective-C, we use a pointer which needs memory management by ARC. There are only a few exceptions where values are used instead of objects, most notable primitive types like <em>BOOL</em> and <em>NSInteger</em>, and simple structures like <em>CGPoint</em>, <em>CGSize</em> and <em>CGRect</em>.</p><p><strong>Swift has a focus on values. </strong>While it is still possible to define classes, the basic types of Swift are structures or enumerations that are passed around by value. The compiler may use references for performance, but that’s not our job anymore.</p><p>While values are easier to understand and to use than references, coming from Objective-C we are used to reference types. It may be confusing to see the semantics change. To illustrate the problem, let’s have a look at an example where we store a mapping from string to an array of strings. Here is the Objective-C code:</p><pre>@interface StringLists : NSObject<br> <br>- (void)addString:(NSString *)string forKey:(NSString *)key;<br>- (NSArray *)listForKey:(NSString *)key;<br> <br>@end<br> <br>@implementation StringLists {<br>    NSMutableDictionary *_stringLists;<br>}<br> <br>- (instancetype)init {<br>    self = [super init];<br>    if (self) {<br>        _stringLists = [NSMutableDictionary new];<br>    }<br>    return self;<br>}<br> <br>- (void)addString:(NSString *)string forKey:(NSString *)key {<br>    NSMutableArray *list = _stringLists[key];<br>    if (list == nil) {<br>        list = [NSMutableArray new];<br>        _stringLists[key] = list;<br>    }<br>    [list addObject:<strong>[string copy]</strong>];<br>}<br> <br>- (NSArray *)listForKey:(NSString *)key {<br>    return <strong>[_stringLists[key] copy]</strong>;<br>}<br> <br>@end</pre><p>Notice the two <em>copy</em> calls. The first one prevents users of the class to accidently pass us an <em>NSMutableString</em> that they mutate afterwards. The second one is not strictly necessary, but a precaution against someone casting and changing the mutable array afterwards.</p><p>If we translate the Objective-C code one-to-one to Swift, a first try may look like this:</p><pre>class StringLists {<br>    var stringLists: [String: [String]] = [:]<br> <br>    func addString(string: String, forKey key: String) {<br>        var list = stringLists[key]<br>        if !list {<br>            list = []<br>            stringLists[key] = list<br>        }<br>        <strong>list!.append(string) // COMPILER ERROR</strong><br>    }<br> <br>    func listForKey(key: String) -&gt; [String]? {<br>        return stringLists[key]<br>    }<br>}</pre><p>In Swift, arrays, dictionaries and strings are structures with value-semantics. That means we don’t need to copy anymore. But that also means that coming from Objective-C, things may not behave as we would expect. The first gotcha is the compiler error. That’s because the forced value expression <em>list!</em> returns a value that we cannot mutate, comparable to C and Objective-C where we can’t mutate a value returned from a function directly. Here is some Objective-C code we would not expect to work:</p><pre>[array count]++; // COMPILER ERROR<br>[view frame].size = CGSizeZero; // COMPILER ERROR</pre><p>While the Swift compiler may change in the future to allow mutation of <em>list!</em>, for now we have to store it in a variable first:</p><pre>func addString(string: String, forKey key: String) {<br>    var list = stringLists[key]<br>    if !list {<br>    list = []<br>       stringLists[key] = list<br>    }<br>    <strong>var unwrappedList = list!<br></strong>    <strong>unwrappedList.append(string)</strong><br>}</pre><p>But that would not work as well. A comparable error in Objective-C would be to try to set the size of a view’s <em>frame</em> to <em>CGSizeZero</em> like this:</p><pre>CGRect frame = [view frame];<br>frame.size = CGSizeZero;</pre><p>What’s of course missing is that we need to write the changed value back:</p><pre>CGRect frame = [view frame];<br>frame.size = CGSizeZero;<br><strong>[view setFrame:frame];</strong></pre><p>As arrays in Swift have value semantics, we need to write the changed value back as well:</p><pre>func addString(string: String, forKey key: String) {<br>    var list = stringLists[key]<br>    if !list {<br>        list = []<br>        stringLists[key] = list<br>    }<br>    var unwrappedList = list!<br>    unwrappedList.append(string)<br>    <strong>stringLists[key] = unwrappedList<br></strong>}</pre><p>Now the code works, but it looks a bit messy. That’s because we translated from Objective-C one-to-one. Let’s clean it up:</p><pre>func addString(string: String, forKey key: String) {<br>    if var list = stringLists[key] {<br>        list.append(string)<br>        stringLists[key] = list<br>    } else {<br>        stringLists[key] = [string]<br>    }<br>}</pre><p>What we should remember: <strong>In Swift, arrays, dictionaries, and strings have value semantics.</strong></p><p>While I was writing this article (before Xcode 6 beta 3), the array in Swift behaved in a way that most developers found strange. Now have sane value semantics for the array.</p><p>Still, I could not resist writing a bit about the old array semantics, and for which scenarios it made sense. That’s not relevant for today’s understanding of Swift though, so feel free to skip the last section below, and continue reading <a href="https://medium.com/@tammofreese/facets-of-swift-part-4-functions-3cce9d9bba4">the next article of this series on functions</a>!</p><h3>Bonus Track: Swift’s Old Array</h3><p>Before the third beta of Swift, the <em>Array</em> type had a behavior that most developers found weird. If we had a constant array defined with <em>let</em>, we could still change the values in the array, but we could not change its size. So this actually worked before:</p><pre>let x = [2006, 90, 74, 54]<br>x.sort(&lt;)<br>x[3] = 2014<br>println(x) // Printed [54, 74, 90, 2014]</pre><p>What we could not do is change the size of the “constant” array, that is, we could not append a value, for example.</p><p>This behavior could actually be explained quite easily: <strong>An Array in Swift was like a struct with a pointer to the internal storage.</strong> With that in mind, everything made sense: a “change” would mean a change to the pointer, and that was only needed if the length of the array changed.</p><p>So why would anyone embrace such a weird behavior? My guess is not only performance, but that it simplified implementing functions that worked on arrays. If we used a range subscript on an array, we got back a slice that still allowed changing the original array:</p><pre>let x = [54, 74, 90, 2006]<br>let last = x[3..4]<br>last[0] = 2014<br>println(x) // Printed [54, 74, 90, 2014]</pre><p>Because of that, we could use slices as views on the original array, which simplified implementing algorithms like quicksort. Normally, recursive implementations start out like this:</p><pre>// CAREFUL: This was valid Swift before beta 3,<br>// it does not work anymore<br> <br>func quicksort(v: Int[]) {<br>    quicksort(<strong>v, 0, v.count — 1</strong>)<br>}<br> <br>func quicksort(<strong>v: Int[], left: Int, right: Int</strong>) {<br>    if left &gt;= right { return }<br>    <br>    let pivotIndex = partition(<strong>v, left, right</strong>)<br>    quicksort(<strong>v, left, pivotIndex - 1</strong>)<br>    quicksort(<strong>v, pivotIndex + 1, right</strong>)<br>}</pre><p>Both <em>quicksort</em> and <em>partition</em> have three input parameters. With the old Swift array behavior, we could use slices instead:</p><pre>// CAREFUL: This was valid Swift before beta 3,<br>// it does not work anymore<br> <br>func quicksort(v: Int[]) {<br>    quicksort(<strong>v[0..v.count]</strong>)<br>}<br> <br>func quicksort(<strong>v: Slice&lt;Int&gt;</strong>) {<br>    if v.count &lt;= 1 { return }<br>   <br>    let pivotIndex = partition(<strong>v</strong>)<br>    quicksort(<strong>v[0..pivotIndex]</strong>)<br>    quicksort(<strong>v[(pivotIndex + 1)..v.count]</strong>)<br>}</pre><p>Suddenly the code is more readable, because the slice parameter abstracted away the <em>left</em> and <em>right</em> offset: Instead of <em>left</em>, we could use 0, instead of <em>right + 1</em>, we could use the <em>count</em> of the slice. That simplifies writing the <em>partition</em> function, because we don’t have to make a lot of index calculations.</p><p>Still, we should be very happy about the change, because now a constant array is immutable, as it should be.</p><p>I hope you enjoyed the article, and learned a thing or two you didn’t know. The <a href="https://medium.com/@tammofreese/facets-of-swift-part-4-functions-3cce9d9bba4">next article of this series</a> is about functions in Swift. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2aac239d6f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/facets-of-swift-part-3-values-and-references-d2aac239d6f4">Facets of Swift, Part 3: Values and References</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facets of Swift, Part 2: Tuples]]></title>
            <link>https://medium.com/swift-programming/facets-of-swift-part-2-tuples-4bfe58d21abf?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bfe58d21abf</guid>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Sun, 06 Jul 2014 21:59:07 GMT</pubDate>
            <atom:updated>2014-12-07T22:29:01.894Z</atom:updated>
            <content:encoded><![CDATA[<p>Facets of Swift is a series of articles on various aspects of the Swift programming language. I write these articles to organize my thoughts on Apple’s new programming language.</p><p>This second article is about Swift’s tuples. Tuples allow us to write more compact code. In addition to that, tuples are a prerequisite to understanding functions, methods and closures, which will be the topic of later articles.</p><h3>What is a Tuple?</h3><p>We may remember the concept of tuples from math or computer science. There, a tuple is simply an ordered list of values, where the type of each value is fixed. In Swift, it’s about the same. To build an n-tuple, we just put the values in parentheses:</p><pre>var result = <strong>(</strong>200, &quot;OK&quot;, true<strong>)</strong></pre><p>Here <em>result</em> is a 3-tuple that holds three values: <em>200</em> (an <em>Int</em>), <em>“OK” </em>(a <em>String</em>) and <em>true</em> (a <em>Bool</em>). The variable <em>result</em> has a tuple type. To declare a tuple type, we use parentheses as well:</p><pre>var result: <strong>(</strong>Int, String, Bool<strong>)</strong><br>result = (200, &quot;OK&quot;, true)</pre><h3>Accessing Tuple Elements</h3><p>The most common method of accessing a tuple’s elements is by decomposing the tuple:</p><pre>var result = (200, &quot;OK&quot;, true)<br>let (statusCode, statusMessage, hasBody) = result</pre><p>Now the three constants <em>statusCode</em>, <em>statusMessage</em>, and <em>hasBody</em> have the values <em>200</em>, <em>“OK”</em>, and <em>true</em>. If we are not interested in a value, we can use an underscore instead of an identifier, the so-called <em>wildcard expression</em>:</p><pre>var result = (200, &quot;OK&quot;, true)<br>let (statusCode, <strong>_</strong>, <strong>_</strong>) = result</pre><p>We can also access the elements of a tuple by their index:</p><pre>var result = (200, &quot;OK&quot;, true)<br>let statusCode = result<strong>.0</strong></pre><p>If a tuple is variable, we can initialize the tuple by setting the elements:</p><pre>var result: (Int, String, Bool)<br>result<strong>.0</strong> <strong>=</strong> 200<br>result<strong>.1</strong> <strong>=</strong> “OK”<br>result<strong>.2</strong> <strong>=</strong> true</pre><h3><strong>Naming Tuple Elements</strong></h3><p>Of course, the last example is not self-documenting: It’s hard to understand what it is about as the elements of the tuple are not named. Well, we can do that:</p><pre>var result: (<strong>statusCode:</strong> Int, <strong>statusText:</strong> String, <strong>hasBody:</strong> Bool)<br>result<strong>.statusCode</strong> <strong>=</strong> 200<br>result<strong>.statusText</strong> <strong>=</strong> “OK”<br>result<strong>.hasBody</strong> <strong>=</strong> true</pre><p>To define the variable <em>result</em> in a shorter way, we can also use type inference:</p><pre>var result = (statusCode: 200, statusText: &quot;OK&quot;, hasBody: true)</pre><p>We don’t have to name all elements of the tuple. You can think of the element names as add-on parts of the tuple type. Provided that tuple length and types match, the assignment will work as long as there are no name conflicts:</p><pre>var result = (statusCode: 200, statusText: &quot;OK&quot;, true)<br>var result2 = (statusCode: 404, &quot;Not Found&quot;, hasBody: true)</pre><pre>result = result2                             // OK<br>result2 = result                             // OK<br>result = (code: 200, statusText: &quot;OK&quot;, true) // ERROR</pre><p>Later on we’ll see why this is a good choice. What we’ve seen so far: <strong>Tuples in Swift can be used to group, and optionally name, related values.</strong></p><p>Before we dive into the various usage scenarios of tuples in Swift, let’s have a look at two special cases: The tuple with no elements and the tuple with only one element.</p><h3>Not that Special: The 0-Tuple</h3><p>As a tuple is a list of elements, can we define an empty tuple, that is a tuple with no elements? Yes we can:</p><pre>var empty: <strong>()</strong><br>empty = <strong>()</strong></pre><p>The code above defines the variable <em>empty</em> to hold the so-called empty tuple type, and afterwards assigns the empty tuple to it. <strong>The empty tuple in Swift is not special, it’s just a tuple with no elements.</strong></p><p>There is a <em>typealias</em> in Swift for the empty tuple type called <em>Void</em>:</p><pre>var empty: <strong>Void</strong><br>empty = ()</pre><p>Note that you can’t use <em>Void</em> as value: It is a type, not a value. So this won’t compile:</p><pre>var empty: Void    // OK<br>empty = Void       // COMPILER ERROR</pre><p>The only difference of the empty tuple to a tuple with two or more elements is that the compiler currently gives us a warning if the empty tuple type is inferred from the empty tuple: If you compile this:</p><pre>var empty = ()</pre><p>the compiler will give you a warning: <em>“Variable ‘empty’ inferred to have type ‘()’, which may be unexpected”</em>.</p><p>Now that we know about the 0-tuple, what about the 1-tuple?</p><h3>Special: The 1-Tuple</h3><p>In contrast to the empty tuple or tuples with two elements or more, the 1-tuple is really special. Because there is no 1-tuple in Swift. If we declare</p><pre>var a: Int<br>var b: (Int)<br>var c: ((((((((((Int))))))))))<br>var d = 42<br>var e = (42)<br>var f = ((((((((((42))))))))))</pre><p>all the variables <em>a</em> to <em>f </em>all have the same type: <em>Int</em>. At first, this may feel like a horrible inconsistency. But it’s not.</p><p>First, depending on your background, it may not feel like an inconsistency. In some parts of math and computer science, an n-tuple type is a product of n types: <em>T = T1 </em>x<em> … </em>x<em> Tn</em>. A 1-tuple would consequently be the type itself: <em>T</em> = <em>T1</em>. So with that background, it feels right that there is no 1-tuple.</p><p>Second, if parentheses around a single element would return a tuple type, we could not use parentheses to group anything. Here are a two examples:</p><pre>var mapping: (Int -&gt; Int)?</pre><p>The variable <em>mapping</em> is an optional function from <em>Int</em> to <em>Int</em>. If parentheses around a single element would return a tuple type, we would not be able to define the type of the variable <em>mapping</em>.</p><pre>var n = 5<br>var sumOfNumbersToN = (n * (n + 1)) / 2</pre><p><em>sumOfNumbersToN</em> is inferred to the type <em>Int</em>. That’s how it should be. If parentheses around a single element would return a tuple type, we would get in trouble as multiplication and division would have to be defined on tuple types as well, and <em>sumOfNumbersOfN</em> would maybe end up to be a tuple type.</p><p>To summarize: <strong>There is no 1-tuple in Swift, only the value itself. There is no 1-tuple type in Swift, only the type itself.*</strong></p><p>(* but read the bonus track at the end of this article on how the beta 4 compiler disagrees with that)</p><p>Now let’s have a look where tuples are used in Swift.</p><h3>When to Use Tuples</h3><p>As tuples form a group of elements, they are used in all places where such a group is useful. The first and simplest use for tuples is multiple assignment. Instead of</p><pre>var x = 1<br>var y = 2<br>var z = 3</pre><p>we can write</p><pre>var (x, y, z) = (1, 2, 3)</pre><p>The second use is to return multiple values from a function. Imagine in our app we often need both the result of the division and the remainder for integers <em>a</em> and <em>b:</em></p><pre>let quotient = a / b<br>let remainder = a % b<br>println(quotient, remainder)</pre><p>So we define a function that returns both in a tuple:</p><pre>func divmod(a: Int, b: Int) -&gt; (quotient: Int, remainder: Int) {<br>    return (a / b, a % b)<br>}</pre><p>(Sidenote: I am aware that this should rather be an extension on <em>Int</em>, or a custom operator, but those are topics for future articles.)</p><p>Now we can decompose the result of the function:</p><pre>let (quotient, remainder) = divmod(a, b)<br>println(quotient, remainder)</pre><p>Alternatively, we can store the tuple result of the call, and access the individual elements:</p><pre>let result = divmod(a, b)<br>println(result.quotient, result.remainder)</pre><p>The above example illustrates why Swift’s designers chose to make assignment work from non-named tuple elements to named tuple elements and vice versa: If we would be forced to match the names, neither the <em>return</em> statement of the function, nor the decomposition of the function’s result would work.</p><p>The third use of tuples is when iterating an array or dictionary. Inside the <em>for…in</em> statement, we use tuple decomposition:</p><pre>for (key, value) in dict {<br>    // ...<br>}<br>for (index, value) in enumerate(array) {<br>    // ...<br>}</pre><p>Instead of the decomposition, we could get the tuples as well:</p><pre>for keyValueTuple in dict {<br> // ...<br>}<br>for indexValueTuple in enumerate(array) {<br> // ...<br>}</pre><p>The fourth use of tuples is in <em>switch</em> statements. Swift’s <em>switch</em> statements are very powerful. They can also match tuples. Here is an example showing the power of the matching:</p><pre>var point = (x: 5, y: 5)<br>switch point {<br>case (0, 0):                        // (1)<br>    println(&quot;Origin&quot;)<br>case (_, 0):                        // (2)<br>    println(&quot;On x-axis&quot;)<br>case (0, _):                        // (2)<br>    println(&quot;On y-axis&quot;)<br>case let (x, y) where x == y:       // (3)<br>    println(&quot;On 1. diagonal&quot;)<br>case let (x, y) where x == -y:      // (3)<br>    println(&quot;On 2. diagonal&quot;)<br>case (-1...1, -1...1):              // (4)<br>    println(&quot;Near origin&quot;)<br>default:                            // (5)<br>    ()    <br>}</pre><p>The above example shows matching a tuple with concrete values for the elements <em>(1)</em>, using the wildcard operator <em>(2)</em>, using binding and a <em>where</em> statement <em>(3)</em>, as well as using ranges <em>(4)</em>.</p><p>If you wonder about the parentheses after <em>default</em> <em>(5)</em>, that’s the empty tuple. In Swift it is not allowed to have a <em>case</em> or <em>default</em> in a <em>switch</em> statement without a following expression, and the empty tuple <em>()</em> is a short, valid expression. You can also use <em>0</em> if you prefer.</p><p>As we know from C and other languages, <em>default</em> matches everything that’s not handled in the cases above. If Swift would not have a <em>default</em> keyword, we could use <em>case (_, _)</em> or <em>case _</em> instead.</p><h3>When Not to Use Tuples</h3><p>At the time of writing, Swift is only a couple of weeks old, so take the following recommendations with a grain of salt.</p><p>Tuples allow us to group related values easily, but we should not use them to replace better suited data structures. There are some indications when you may prefer a data structure to a tuple type:</p><ul><li>The strongest indication is that you have a good name for the group of elements of a tuple. Then choose a <em>struct</em> or <em>class</em> with that name.</li><li>If you would like to define functions that take the tuple as a parameter, try to come up with a name for a <em>struct</em> or <em>class</em>, and define the function as a method on that type.</li><li>If the tuple contains elements which are optional and mutually exclusive: An <em>enum</em> is a better way to express that.</li></ul><p>That’s it for this article. I tried to only show what’s documented about Swift’s tuples. However, there are some things I stumbled upon when writing the fourth part of this series, which I summarized in the following section. Beware: It is not needed to do Swift programming, it’s purely based on pushing the boundaries of a new language that’s still in flux. It may be confusing. So you may skip the last section and continue reading the <a href="https://medium.com/swift-programming/facets-of-swift-part-3-values-and-references-d2aac239d6f4">next article of this series</a>, where we will have a look at values and references in Swift.</p><h3>Bonus Track: Tuples All the Way Down</h3><p>Still here? Great! Let’s have a look at a variable declaration:</p><pre>var foo: <strong>(Int)</strong> = 42</pre><p>The Swift Programming Language iBook tells us if we use <em>(Int)</em> it is simply <em>Int</em>, not <em>(Int)</em>. Also, it tells us that as a result, we can only name tuple elements if there are at least two elements.</p><p>Well, let’s see whether the compiler disagrees with the documentation:</p><pre>var foo: <strong>(x: Int)</strong> = 42<br>println(foo<strong>.x</strong>)<br>println(foo<strong>.0</strong>)</pre><p>It does: This works fine and prints <em>42</em> two times. So yes, we can name tuple elements if there is only one element in the tuple, and yes, there seems to be a named 1-tuple in Swift. In the fourth article of this series, we’ll see an explanation why the existence of a named 1-tuple makes sense.</p><p>Let’s check again whether there is a 1-tuple:</p><pre>var foo: <strong>(Int)</strong> = 42<br>println(foo<strong>.0</strong>)</pre><p>Wait, what? That works fine as well. The documentation says <em>(Int)</em> is simply <em>Int</em>. Maybe it’s the other way round? Maybe <em>Int</em> is <em>(Int)</em>? Maybe <em>everything is a tuple</em>?</p><pre>var foo: <strong>Int</strong> = 42<br>println(foo<strong>.0</strong>)</pre><p>Works fine as well. But that’s not all. If <em>Int</em> is <em>(Int)</em> then shouldn’t it by induction also be <em>((Int))</em>? Or even <em>((((((((((Int))))))))))</em>?</p><pre>var foo: Int = 42<br>println(foo<strong>.0.0</strong>)<br>println(foo<strong>.0.0.0.0.0.0.0.0.0.0</strong>)</pre><p>It is. <strong>In Swift, there are tuples all the way down. At least in beta 4.</strong></p><p>In the <a href="https://medium.com/swift-programming/facets-of-swift-part-3-values-and-references-d2aac239d6f4">next article of this series</a>, we will have a look at values and references in Swift.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bfe58d21abf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/facets-of-swift-part-2-tuples-4bfe58d21abf">Facets of Swift, Part 2: Tuples</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facets of Swift, Part 1: Optionals]]></title>
            <link>https://medium.com/swift-programming/facets-of-swift-part-1-optionals-b8ba5b0051a2?source=rss-84cc0d5dfb3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8ba5b0051a2</guid>
            <dc:creator><![CDATA[Tammo Freese]]></dc:creator>
            <pubDate>Thu, 26 Jun 2014 19:27:40 GMT</pubDate>
            <atom:updated>2014-12-01T17:29:02.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Facets of Swift is a series of articles on various aspects of the Swift programming language. I chose optionals as the topic for the first article, as these are one of the first features of Swift you will notice. The idea of optionals is simple: To prevent errors and to model things in code more accurately, Swift distinguishes between optional and non-optional values.</p><h3>What are Optionals?</h3><p>In Objective-C, there is no explicit optional value. To illustrate where that can pose problems, let’s have a look at a method that returns the index of an item in a todo list:</p><pre>- (<strong>NSInteger</strong>)indexOfItem:(<strong>Item *)item</strong> {<br>    // ...<br>}</pre><p>Here, the item is implicitly optional: We can either pass an instance of <em>Item</em>, or <em>nil</em>. On the other hand, the return value is implicitly non-optional: As <em>NSInteger</em> is not an object type, there is no way not to return a value.</p><p>For the <em>item</em> parameter, it would make sense to require a non-<em>nil</em> value. But that’s not possible in Objective-C. For the return value, it would make sense to be able to return <em>nil</em> if the item is not in the list. But that’s not possible in Objective-C. We can only add documentation what happens if a <em>nil</em> is passed as an item (error or not?), and which value is returned in case the item is not in the list (<em>NSNotFound</em> which is defined as <em>NSIntegerMax</em>? Or <em>NSIntegerMin</em>? Or <em>-1</em>?).</p><p>Wouldn’t it be great if we had to explicitly write down which values are optional? Well, that’s the case in Swift. A type <em>T</em> is non-optional. To allow the absence of a value, we use the optional type <em>T?</em>. We may define the method like this:</p><pre>func indexOfItem(<strong>item: Item</strong>) -&gt; <strong>Int?</strong> {<br>    // ...<br>}</pre><p>Here the method declaration requires that we pass an item. Trying to pass <em>nil</em> would result in a compile-time error. Also, the method explicitly expresses that the return value is optional, so we don’t need to define a special <em>Int</em> value to model the absence of the index.</p><p>A variable <em>v</em> of type <em>T?</em> has a couple of differences to a variable of non-optional type <em>T</em>:</p><ol><li>It can not only hold values of type <em>T</em>, but also the empty value <em>nil</em>.</li><li>It is initialized to <em>nil</em>.</li><li>To access the value of type <em>T</em> which may be stored in <em>v</em>, we have to unwrap the value first.</li></ol><h3>Unwrapping Optionals</h3><p>Let’s say we would like to write a method that returns the one-based index of the item in a list (let’s call it the natural index, because it is more natural to start counting from 1). In Objective-C, the implementation may look like this:</p><pre>- (NSInteger)naturalIndexOfItem:(Item *)item {<br>    NSInteger indexOrNotFound = [self indexOfItem:item];<br>    if (indexOrNotFound != NSNotFound) {<br>        return indexOrNotFound + 1;<br>    } else {<br>        return NSNotFound;<br>    }<br>}</pre><p>If we write the respective code in Swift, a first attempt may look like this:</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    let indexOrNotFound = indexOfItem(item)<br>    <strong>if indexOrNotFound != nil</strong> {<br>        let index = <strong>indexOrNotFound!</strong><br>        return index + 1<br>    } else {<br>        return nil<br>    }<br>}</pre><p>The <em>!</em> behind <em>indexNotFound</em> unwraps the optional value to a non-optional. So <em>index</em> has the type <em>Int</em>, and the compiler does not complain about the addition.</p><p>If <em>indexOrNotFound</em> would be <em>nil</em>, then unwrapping would fail with a runtime error. The expression <em>indexNotFound!</em> is for that reason called a <em>forced-value expression</em>.</p><h3>Optional Binding</h3><p>Of course, the first attempt is not the best solution: The code is now longer than in Objective-C. We can do much better. First, as we often need to unwrap a value and then use it, Swift provides something called <em>optional binding</em>:</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    let indexOrNotFound = indexOfItem(item)<br>    <strong>if let</strong> index = indexOrNotFound {<br>        return index + 1<br>    } else {<br>        return nil<br>    }<br>}</pre><p>If we use <em>let</em> or <em>var</em> in the condition of an <em>if</em> statement, the constant/variable is set to the unwrapped value, so we don’t need to unwrap anymore. We can now inline <em>indexOrNotFound</em>:</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    if let index = indexOfItem(item) {<br>        return index + 1<br>    } else {<br>        return nil<br>    }<br>}</pre><p>Instead of adding <em>1</em>, we can call <em>successor()</em> on <em>index</em>:</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    if let index = indexOfItem(item) {<br>        return index<strong>.successor()</strong><br>    } else {<br>        return nil<br>    }<br>}</pre><p>But even that is way too much code in Swift. Enter <em>optional chaining</em>.</p><h3>Optional Chaining</h3><p>The essence of the method above is calling the <em>successor</em> function on <em>indexOfItem(item)</em>. The rest is just the handling of the optional value. However, we can’t write</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    return indexOfItem(item).successor()<br>}</pre><p>That will lead to a compiler error, as the method <em>successor</em> is not defined on the optional type returned by <em>indexOfItem(item)</em>. And it should not compile, as we ignored the optional case. What about unwrapping with the forced value expression?</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    return indexOfItem(item)<strong>!.</strong>successor()<br>}</pre><p>Now as soon as the item is not in the list, we would get a runtime error. What works is optional chaining which is done with <em>?</em>:</p><pre>func naturalIndexOfItem(item: Item) -&gt; Int? {<br>    return indexOfItem(item)<strong>?.</strong>successor()<br>}</pre><p>If an object <em>a</em> is of optional type, <em>a?.b</em> returns <em>nil</em> if <em>a</em> is <em>nil</em>, otherwise it returns <em>b</em>. In Objective-C we have implicit optional chaining on objects: If we have a variable <em>item</em> that holds an item or <em>nil</em>, which can belong to a list or not, and a list can have a name or not, we get the name of the list or <em>nil</em> by calling</p><pre>NSString *listName = item<strong>.</strong>list<strong>.</strong>name;</pre><p>In Swift, for the same case we would need to write:</p><pre>var listName = item<strong>?.</strong>list<strong>?.</strong>name</pre><p>Is that preferable? Yes, it is. We have to explicitly state how we handle optional values. Even better, we can narrow down which parts are really optional and which aren’t. We can get rid ot the first question mark by making <em>item</em> a non-optional variable. We can get rid of the second question mark by making the <em>list</em> property non-optional. Finally, we can make the variable <em>listName</em> a <em>String </em>instead of a <em>String?</em> by making the<em> name</em> property non-optional.</p><p>Bottom line: <strong>In Objective-C, we can’t make objects non-optional and we can’t make other types optional. In Swift, we can.</strong></p><h3>Implicitly Unwrapped Optionals</h3><p>There is a second optional type in Swift: The implicitly unwrapped optional. It is needed for various reasons, one of them is better compatibility with Objective-C libraries. A good example is the method <em>+currentDevice</em> on <em>UIDevice</em>. In Objective-C, it looks like this:</p><pre>+ (UIDevice *)currentDevice;</pre><p>How could the signature of such a method be bridged to Swift? First try:</p><pre>class func currentDevice() -&gt; <strong>UIDevice</strong></pre><p>That won’t work. While we are pretty sure that currentDevice will always return a value, that is not true for all Objective-C methods and properties. For example, both the method <em>anyObject</em> on <em>NSSet</em> and the property <em>superview</em> on <em>UIView</em> may be <em>nil</em>.</p><p>We could use an optional:</p><pre>class func currentDevice() -&gt; <strong>UIDevice?</strong></pre><p>That would work fine. The disadvantage is that our code would be cluttered with lots of unwrapping, optional chaining and so on, even though most of the methods in <em>UIKit</em> return non-nil objects. Imagine we would like to have the name of the current device as an NSString. Even though we know that both the device and its name are not <em>nil</em>, we would have to write:</p><pre>var name = UIDevice.currentDevice()<strong>!</strong>.name<strong>!</strong></pre><p>Not pretty. What we would like to have is something that can still be <em>nil</em>, but that we do not have to unwrap ourselves. That’s the implicitly unwrapped optional, which is marked with an exclamation mark:</p><pre>class func currentDevice() -&gt; <strong>UIDevice!</strong></pre><p>A variable <em>v</em> of type <em>T!</em> has one difference to a variable of optional type <em>T?</em>: It will be implicitly unwrapped to type <em>T</em>. Because of that, we don’t need to unwrap anything here:</p><pre>var name = UIDevice.currentDevice().name</pre><p><em>name</em> will now inferred to be of type <em>NSString!</em>, but that’s not a problem since it will be automatically unwrapped when it is accessed.</p><p>So whenever we have an Objective-C method or property that we know will not return <em>nil</em>, we can use it just like a non-optional. If we know that the value may be <em>nil</em>, we can use optional binding and chaining to prevent runtime errors.</p><p>The implicitly unwrapped optional has not been added for Objective-C support alone, though. In Swift it helps us with chicken-egg problems where an object needs a reference to another object which is not available at initialization time. The simplest example I could come up with is a recursive closure. Let’s say we would like to define factorial, and print out<em> factorial(12)</em>. First try:</p><pre>var factorial: Int -&gt; Int<br>factorial = { x in (x == 0) ? 1 : x * factorial(x — 1) }<br>println(factorial(12))</pre><p>The compiler will rightly complain that we can’t use factorial inside the closure, because at that point, the variable is not initialized. We could work around by making <em>factorial</em> an optional:</p><pre>var factorial: <strong>(</strong>Int -&gt; Int<strong>)?</strong><br>factorial = { x in (x == 0) ? 1 : x * factorial<strong>!</strong>(x — 1) }<br>println(factorial<strong>!</strong>(12))</pre><p>Now our code is cluttered with unwrapping even though it is glaringly obvious that <em>factorial</em> will be defined when accessed. An implicitly unwrapped optional is the best solution:</p><pre>var factorial: (Int -&gt; Int)<strong>!</strong><br>factorial = { x in (x == 0) ? 1 : x * factorial(x — 1) }<br>println(factorial(12))</pre><p><strong>In Swift, we have non-optionals, optionals and implicitly unwrapped optionals.</strong></p><p>Optionals of Bool values are quite interesting, as these give us three choices. Let’s have a look on how to cover these three choices in code.</p><h3>Optional Bool</h3><p>If we use an optional boolean type (<em>Bool?</em>), it can be unwrapped to <em>true</em> or <em>false</em>, or be <em>nil</em>. There are a couple of ways to cover all three cases. We can unwarp the optional variable:</p><pre>var authenticated: Bool? = false<br>if <strong>let authenticated = authenticated</strong> {<br>    if <strong>authenticated</strong> {<br>        println(&quot;Authenticated&quot;)<br>    } else {<br>        println(&quot;Not authenticated&quot;)<br>    }<br>} else {<br>    println(&quot;Unknown&quot;)<br>}</pre><p>If we don’t like the structure of the code, we can cover the three cases on the same level:</p><pre>var authenticated: Bool? = false<br>if <strong>authenticated == true</strong> {<br>    println(“Authenticated”)<br>} else if <strong>authenticated == false</strong> {<br>    println(“Not authenticated”)<br>} else {<br>    println(“Unknown”)<br>}</pre><p>We need the comparisons above as <em>authenticated</em> is an optional, and since Swift beta 5, we can’t use optionals directly as logic values, however, we can use them directly in comparisons with <em>==</em>. Besides, the respective Objective-C code using <em>NSNumber *authenticated</em> would definitely look worse.</p><p>If we prefer to, we can also use a <em>switch</em> statement.</p><pre>var authenticated: Bool? = false<br>switch authenticated {<br>case <strong>.Some(true)</strong>:<br>    println(“Authenticated”)<br>case <strong>.Some(false)</strong>:<br>    println(“Not authenticated”)<br>default:<br>    println(“Unknown”)<br>}</pre><p>I don’t like it that much though for a couple of reasons. First, we have to use <em>.Some</em> which is part of the implementation of optionals (it’s done with an <em>enum</em> type, but that’s a story for another article). Second, even if we cover all three possible cases in the <em>switch</em> statement, the compiler will complain we have not exhausted all cases. That’s because of the current internals of <em>Bool</em>. Don’t ask. So we have to use a <em>default</em> instead of the third <em>case</em>.</p><p>What about other gotchas with Swift’s optionals?</p><h3>Gotchas</h3><p>Having optionals is something we don’t have in Objective-C, so a couple of things may be confusing at first. The biggest gotcha is that question mark and exclamation mark as postfix on a type <em>T</em> are quite different to their counterparts used on an expression <em>v</em>:</p><ul><li><em>T?</em> is the optional type</li><li><em>T!</em> is the implicitly unwrapped optional type</li><li><em>v?</em> is used for optional chaining</li><li><em>v!</em> is used for unwrapping</li></ul><p>Things that may be confusing here:</p><ul><li>If we have a non-optional type <em>T</em>, we can use <em>?</em> and <em>!</em> on it. If we have an expression <em>v</em> of non-optional type <em>T</em>, we can’t use <em>?</em> and <em>!</em> on it, as both chaining and unwrapping don’t make sense on a non-optional.</li><li>We can use <em>!</em> on both expressions of type <em>T!</em> and <em>T?</em></li><li>We can use <em>?</em> on both expressions of type <em>T? </em>and <em>T!</em></li></ul><p>The last bit of confusion is the behavior of the <em>?</em> postfix on an expression <em>v</em> if we use it without calling anything on it. Then it just returns <em>v</em> as an optional. So if <em>v</em> is either of type <em>Int?</em> or of type <em>Int!</em>, and we declare</p><pre>var v2 = v?<br>var v3 = v???????????</pre><p>, both <em>v2</em> and <em>v3</em> will be of type <em>Int?</em>.</p><h3>Recommendations for using Optionals</h3><p>At this point, Swift is only a couple of weeks old. So take the following recommendations with a grain of salt.</p><p>First, don’t use the optional chaining operator ? on its own, but always with a following dot. Its name already points to its main use: optional chaining.</p><p>Second, while technically possible, don’t use optionals of optionals. Yes, you can define something like <em>var v: Int?!!</em>. But don’t. Please don’t.</p><p>Third, try to avoid the implicitly unwrapped optional, except when you’re really sure that it will be always filled. A lot of the Cocoa APIs are still not annotated correctly and return <em>T!</em>, but from a programmer’s perspective, most should either return <em>T?</em>, or <em>T</em>.</p><p>Last but not least, only use optionals where you need them, and where the extra case actually makes sense. For example, if you model a todo list that has a name and items, the <em>items</em> property can always be a non-optional <em>Array</em>. The <em>name</em> property can be a non-optional <em>String</em>. Only make the name optional if you really need to distinguish between a sensible default like the empty <em>String</em> and the case that the name is unset. <strong>Swift’s optionals and implicitly unwrapped optionals are great. But non-optionals are the default for a reason.</strong></p><p>In the <a href="https://medium.com/@tammofreese/facets-of-swift-part-2-tuples-4bfe58d21abf">next article of this series</a>, we’ll have a look at Swift’s tuples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8ba5b0051a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/facets-of-swift-part-1-optionals-b8ba5b0051a2">Facets of Swift, Part 1: Optionals</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>