{"id":1100,"date":"2014-08-04T23:47:53","date_gmt":"2014-08-05T05:47:53","guid":{"rendered":"http:\/\/jamesonquave.com\/blog\/?p=1100"},"modified":"2015-02-03T13:42:47","modified_gmt":"2015-02-03T19:42:47","slug":"swifts-nil-coaelescing-operator-in-xcode-6-beta-5","status":"publish","type":"post","link":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/","title":{"rendered":"Swift&#8217;s Nil Coalescing Operator In Xcode 6 Beta 5"},"content":{"rendered":"<p>I was just updating my tutorial series on <a href='http:\/\/jamesonquave.com\/blog\/developing-ios-apps-using-swift-tutorial\/'>developing iOS 8 apps in Swift<\/a> for Beta 5, and I was looking at this bit of code:<\/p>\n<pre class=\"brush: js;\">\r\nvar name = result[\"trackName\"] as? String\r\nif !name? {\r\n    name = result[\"collectionName\"] as? String\r\n}\r\n<\/pre>\n<p>The code is setting name to the result[&#8220;trackName&#8221;], if it can successfully cast to String. If it can&#8217;t then maybe it&#8217;s blank, or null, or something&#8217;s just not right.<\/p>\n<p>So, then on line 2, it checks to see if name is not set still by using !name?, checking to see if it&#8217;s nil. If so, then switch over to the &#8220;collectionName&#8221; key. Sometime&#8217;s this example API call returned names of songs as &#8220;trackName&#8221;, and sometimes it returned names of albums in the key &#8220;collectionName&#8221;<\/p>\n<p>All this code is really just checking\/setting the variable name in order to get something in there. But it&#8217;s sort of verbose, and the Xcode 6 Beta 5 update actually made optionals no longer conform to BooleanType any more, so this code gives an error on this line:<\/p>\n<pre class=\"brush: js\">\r\nif !name?\r\n<\/pre>\n<p><strong>ERROR: Type &#8216;String?&#8217; does not conform to protocol &#8216;BooleanType.Protocol&#8217;<\/strong><\/p>\n<p><script type=\"text\/javascript\">\n    google_ad_client = \"ca-pub-0669634193877934\";\n    google_ad_slot = \"6023897638\";\n    google_ad_width = 728;\n    google_ad_height = 90;\n<\/script><br \/>\n<!-- 728x90 website ad --><br \/>\n<script type=\"text\/javascript\"\nsrc=\"\/\/pagead2.googlesyndication.com\/pagead\/show_ads.js\">\n<\/script><\/p>\n<p>Apple&#8217;s Beta 5 update notes mentions this change, and the new preferred method of performing this check. From the <a href='http:\/\/adcdownload.apple.com\/\/Developer_Tools\/xcode_6_beta_5_za4gu6\/xcode_6_beta_5_release_notes.pdf'>release notes<\/a>:<\/p>\n<p>&#8220;Optionals no longer conform to the BooleanType (formerly LogicValue) protocol, so they<br \/>\nmay no longer be used in place of boolean expressions (they must be explicitly compared with v != nil). &#8221;<\/p>\n<p>So I could update my code to say something like this:<\/p>\n<pre class=\"brush: js;\">\r\nvar name = result[\"trackName\"] as? String\r\nif name == nil {\r\n    name = result[\"collectionName\"] as? String\r\n}\r\n<\/pre>\n<p>This works, but beta 5 added one more thing, the nil coalescing operator! That&#8217;s quite a mouthful, and if you use that term at parties people will think you&#8217;re super smart. They probably will not want to talk to you much after that, but it&#8217;s just because they are jealous.<\/p>\n<p>Okay, so back on topic. The nil coalescing operator&#8230;<\/p>\n<p>Basically this new operator does the same check as above, but it does it in short form using an operator, <strong>??<\/strong><\/p>\n<p>Placing it between two operands does the check with the left hand value. If it&#8217;s nil it then prefers the right-hand value. So for example, I can rewrite my statement above as the following:<\/p>\n<pre class=\"brush: js;\">\r\nlet trackName = result[\"trackName\"] as? String\r\nlet collectionName = result[\"collectionName\"] as? String\r\nlet name : String = trackName ?? collectionName\r\n<\/pre>\n<p>This code is a bit more concise, with pretty much the same output. I can also easily add a third option to fall back on if for some crazy reason neither of these variables are set:<\/p>\n<pre class=\"brush: js;\">\r\nlet name = trackName ?? collectionName ?? \"Untitled\"\r\n<\/pre>\n<p>By doing this we get an added benefit: the type &#8220;String&#8221; can now be inferred \ud83d\ude42<br \/>\nThe only downside is that both the trackName and collectionName lookups are performed. We could eliminate this as well by rewriting this as a single (slightly harder to read) line.<\/p>\n<pre class=\"brush: js;\">\r\nlet name = (result[\"trackName\"] as? String) ?? (result[\"collectionName\"] as? String) ?? \"Untitled\"\r\n<\/pre>\n<p>But personally, I think it&#8217;s cleaner to leave it as three lines, even if it is slightly less performant.<\/p>\n<p>Looking at the definitions for the ?? operator I see this:<\/p>\n<pre class=\"brush: js;\">\r\ninfix operator ?? {\r\n    associativity right\r\n    precedence 110\r\n}\r\n.....\r\nfunc ??&lt;T&gt;(optional: T?, defaultValue: @autoclosure () -> T) -> T\r\n<\/pre>\n<p>You&#8217;ll notice the left-hand operand is of type T?, and the right-hand operand is of type @autoclosure () -> T. Or in other words, the left-hand side takes an optional, and the right-hand side takes basically any expression (any closure, except you don&#8217;t need to specify it&#8217;s a closure, the @autoclosure keyword turns it in to one.) That means the right-hand operand can take just about any expression, such as:<\/p>\n<pre class=\"brush: js;\">\r\nisEnabled = screenSaverDisabled ?? self.lastTimeSeenMoving > (CACurrentMediaTime()-5)\r\n\r\n\/\/ -or-\r\n\r\nvar someValue = someOptional ?? self.someMethod() ?? self.someProperty\r\n<\/pre>\n<p>The only requirement is that each of these operands are of the same type.<\/p>\n<p>Happy coalescing!<\/p>\n<p>Excited to learn more? Take a look at my <a href='http:\/\/jamesonquave.com\/swiftebook'>upcoming book<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I was just updating my tutorial series on developing iOS 8 apps in Swift for Beta 5, and I was looking at this bit of code: var name = result[&#8220;trackName&#8221;] as? String if !name? { name = result[&#8220;collectionName&#8221;] as? String } The code is setting name to the result[&#8220;trackName&#8221;], if it can successfully cast to&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_links_to":"","_links_to_target":""},"categories":[25,10,32],"tags":[58,33,57],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Swift&#039;s Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Swift&#039;s Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave\" \/>\n<meta property=\"og:description\" content=\"I was just updating my tutorial series on developing iOS 8 apps in Swift for Beta 5, and I was looking at this bit of code: var name = result[&quot;trackName&quot;] as? String if !name? { name = result[&quot;collectionName&quot;] as? String } The code is setting name to the result[&#8220;trackName&#8221;], if it can successfully cast to...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/\" \/>\n<meta property=\"og:site_name\" content=\"Jameson Quave\" \/>\n<meta property=\"article:published_time\" content=\"2014-08-05T05:47:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2015-02-03T19:42:47+00:00\" \/>\n<meta name=\"author\" content=\"Jameson Quave\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Jameson Quave\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/\",\"url\":\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/\",\"name\":\"Swift's Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave\",\"isPartOf\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\"},\"datePublished\":\"2014-08-05T05:47:53+00:00\",\"dateModified\":\"2015-02-03T19:42:47+00:00\",\"author\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc\"},\"breadcrumb\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jamesonquave.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Swift&#8217;s Nil Coalescing Operator In Xcode 6 Beta 5\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\",\"url\":\"https:\/\/jamesonquave.com\/blog\/\",\"name\":\"Jameson Quave\",\"description\":\"Using computer technology to educate, and improve lives.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc\",\"name\":\"Jameson Quave\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/d9786c83345117d560bbeab0e1f26814?s=96&d=retro&r=pg\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/d9786c83345117d560bbeab0e1f26814?s=96&d=retro&r=pg\",\"caption\":\"Jameson Quave\"},\"sameAs\":[\"http:\/\/jamesonquave.com\"],\"url\":\"https:\/\/jamesonquave.com\/blog\/author\/jquave\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Swift's Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/","og_locale":"en_US","og_type":"article","og_title":"Swift's Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave","og_description":"I was just updating my tutorial series on developing iOS 8 apps in Swift for Beta 5, and I was looking at this bit of code: var name = result[\"trackName\"] as? String if !name? { name = result[\"collectionName\"] as? String } The code is setting name to the result[&#8220;trackName&#8221;], if it can successfully cast to...","og_url":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/","og_site_name":"Jameson Quave","article_published_time":"2014-08-05T05:47:53+00:00","article_modified_time":"2015-02-03T19:42:47+00:00","author":"Jameson Quave","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Jameson Quave","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/","url":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/","name":"Swift's Nil Coalescing Operator In Xcode 6 Beta 5 - Jameson Quave","isPartOf":{"@id":"https:\/\/jamesonquave.com\/blog\/#website"},"datePublished":"2014-08-05T05:47:53+00:00","dateModified":"2015-02-03T19:42:47+00:00","author":{"@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc"},"breadcrumb":{"@id":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jamesonquave.com\/blog\/swifts-nil-coaelescing-operator-in-xcode-6-beta-5\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jamesonquave.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Swift&#8217;s Nil Coalescing Operator In Xcode 6 Beta 5"}]},{"@type":"WebSite","@id":"https:\/\/jamesonquave.com\/blog\/#website","url":"https:\/\/jamesonquave.com\/blog\/","name":"Jameson Quave","description":"Using computer technology to educate, and improve lives.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jamesonquave.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc","name":"Jameson Quave","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/d9786c83345117d560bbeab0e1f26814?s=96&d=retro&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d9786c83345117d560bbeab0e1f26814?s=96&d=retro&r=pg","caption":"Jameson Quave"},"sameAs":["http:\/\/jamesonquave.com"],"url":"https:\/\/jamesonquave.com\/blog\/author\/jquave\/"}]}},"_links":{"self":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1100"}],"collection":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/comments?post=1100"}],"version-history":[{"count":24,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1100\/revisions"}],"predecessor-version":[{"id":1614,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1100\/revisions\/1614"}],"wp:attachment":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/media?parent=1100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/categories?post=1100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/tags?post=1100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}