{"id":1032,"date":"2014-07-28T10:40:38","date_gmt":"2014-07-28T16:40:38","guid":{"rendered":"http:\/\/jamesonquave.com\/blog\/?p=1032"},"modified":"2014-12-06T21:35:07","modified_gmt":"2014-12-07T03:35:07","slug":"re-implementing-optionals-using-swifts-powerful-enum-type","status":"publish","type":"post","link":"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/","title":{"rendered":"Re-implementing Optionals using Swift&#8217;s powerful enum type."},"content":{"rendered":"<p><strong><i>This post updated December 6, 2014 to reflect changes in Xcode 6.2<\/i><\/strong><br \/>\n<br \/>\nIf you&#8217;ve been messing with Swift much lately, you may have noticed that enum&#8217;s do <strong>much more<\/strong> than they did in Objective-C, or in most other languages for that matter. In the WWDC videos discussing Swift, one of the presenters mentions that Optionals are implemented as enums. Let&#8217;s explore this a bit and see if we could possibly implement Optionals ourselves, as an exercise in exploring Swift&#8217;s enum type.<\/p>\n<p>The first thing to note about an Apple&#8217;s implementation of Optional is that it&#8217;s an enum with two cases, Some and None. So first off, we create an enum, let&#8217;s call it JOptional, and add these cases.<\/p>\n<pre class=\"brush: js;\">\r\nenum JOptional {\r\n    case None\r\n    case Some\r\n}\r\n<\/pre>\n<p>When we set the enum case to &#8216;Some&#8217;, we should also have an associated value, but it can be any object type. So we use the <strong>T<\/strong> keyword to specify it&#8217;s a generic type.<\/p>\n<pre class=\"brush: js;\">\r\nenum JOptional&lt;T&gt; {\r\n    case None\r\n    case Some(T)\r\n}<\/pre>\n<p>We haven&#8217;t built out any fancy shortcuts that Swift&#8217;s regular optionals use yet, but we can still instantiate JOptionals directly if we add some init() methods.<\/p>\n<pre class=\"brush: js;\">\r\nenum JOptional&lt;T&gt; {\r\n    case None\r\n    case Some(T)\r\n    \r\n    init(_ value: T) {\r\n        self = .Some(value)\r\n    }\r\n    \r\n    init() {\r\n        self = .None\r\n    }\r\n    \r\n}\r\n\r\n\/\/ Instantiate some optionals\r\nvar myOptionalString = JOptional(\"A String!\")\r\nvar myNilString = JOptional()\r\n<\/pre>\n<p>Already we have a bit of a shortcut baked in here. The type of myOptionalString is JOptional&lt;String&gt;, but because we added a init(_ value: T) method to the enum, we can pass in:<\/p>\n<ol>\n<li>An unnamed parameter, due to the use of the _ for external name<\/li>\n<li>Of any type, since it is accepting a generic type of value T<\/li>\n<li>That initializes self, and sets the case to .Some with the attached value<\/li>\n<\/ol>\n<p>Taking a look at the value of myOptionalString (I&#8217;m using a playground for this) you should see (Enum value). This is similar to how Swift&#8217;s optionals are &#8220;wrapped&#8221;. So, we need an unwrap method. Here is what I came up with:<\/p>\n<pre class=\"brush: js;\">\r\nfunc unwrap() -&gt; Any {\r\n    switch self {\r\n    case .Some(let x):\r\n        return x\r\n    default:\r\n        assert(true, \"Unexpectedly found nil while unwrapping an JOptional value\")\r\n    }\r\n    return JOptional.None\r\n}\r\n<\/pre>\n<p>This method uses the value-binding feature of Swift to determine if the enum value can be matched against .Some(let x):<br \/>\nIf it can, then it&#8217;s safe to assume that x actually contains something, and since this is an unwrapping, we can return it.<\/p>\n<p>Otherwise, this falls back to the default case, which is where we need to point out to the developer that they attempted to unwrap a JOptional that wasn&#8217;t able to be bound to x. I added an assert here, I believe this is also present in Apple&#8217;s Optional enum, since a force unwrapping of an Optional produces a hard crash.<\/p>\n<p>We can test this out, like so:<\/p>\n<pre class=\"brush: js;\">\r\nvar myOptionalString = JOptional(\"A String!\")\r\nvar a = myOptionalString.unwrap()\r\n<\/pre>\n<p>The value of a should now be to &#8220;A String!&#8221;, while myOptionalString should still be JOptional.Some(&#8220;A String!&#8221;), which will print as (Enum value).<\/p>\n<p>In Apple&#8217;s Optional, one can unwrap by just appending ! to the end of the variable. We can&#8217;t use this symbol since it&#8217;s reserved, but there&#8217;s no reason we can add &gt;! as a new postfix operator. Why &gt;! you ask? I have no idea, but it&#8217;s not taken. Actually, this is a pretty good example of how to not choose operator overloads, but that&#8217;s okay. No one is ever going to use this, I hope.<\/p>\n<p>On line 1 we create the postfix, then on line 2 we implement the overload to the operator<\/p>\n<pre class=\"brush: js;\">\r\npostfix operator &gt;! {}\r\npostfix func &gt;! &lt;T&gt;(value: JOptional&lt;T&gt; ) -&gt; Any {\r\n    return value.unwrap()\r\n}\r\n<\/pre>\n<p>Now, we can unwrap the optional with our custom operator<\/p>\n<pre class=\"brush: js;\">\r\n\/\/ Instantiate some optionals\r\nvar myOptionalString = JOptional(\"A String!\")\r\nvar a = myOptionalString.unwrap() \/\/ \"A String!\"\r\nvar c = myOptionalString&gt;!     \/\/ \"A String!\"\r\n<\/pre>\n<p><a href=\"https:\/\/github.com\/jquave\/JOptional\/tree\/Part1\">Full code for this part here &raquo;<\/a><\/p>\n<p>This concludes part 1. In the next part we&#8217;ll implement nil comparison using the Equatable and NilLiteralConvertible interfaces.<br \/>\n<a href='http:\/\/jamesonquave.com\/blog\/using-equatable-and-nilliteralconvertible-to-re-implement-optionals-in-swift-part-2\/'>Go To Part 2 &raquo;<\/a><\/p>\n<p>This topic is also explored more in-depth in <a href='http:\/\/jamesonquave.com\/swiftebook\/'>my upcoming book<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post updated December 6, 2014 to reflect changes in Xcode 6.2 If you&#8217;ve been messing with Swift much lately, you may have noticed that enum&#8217;s do much more than they did in Objective-C, or in most other languages for that matter. In the WWDC videos discussing Swift, one of the presenters mentions that Optionals&#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":[10,32],"tags":[56,15,55,33],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Re-implementing Optionals using Swift&#039;s powerful enum type. - 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\/re-implementing-optionals-using-swifts-powerful-enum-type\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Re-implementing Optionals using Swift&#039;s powerful enum type. - Jameson Quave\" \/>\n<meta property=\"og:description\" content=\"This post updated December 6, 2014 to reflect changes in Xcode 6.2 If you&#8217;ve been messing with Swift much lately, you may have noticed that enum&#8217;s do much more than they did in Objective-C, or in most other languages for that matter. In the WWDC videos discussing Swift, one of the presenters mentions that Optionals...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/\" \/>\n<meta property=\"og:site_name\" content=\"Jameson Quave\" \/>\n<meta property=\"article:published_time\" content=\"2014-07-28T16:40:38+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2014-12-07T03:35:07+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\/re-implementing-optionals-using-swifts-powerful-enum-type\/\",\"url\":\"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/\",\"name\":\"Re-implementing Optionals using Swift's powerful enum type. - Jameson Quave\",\"isPartOf\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#website\"},\"datePublished\":\"2014-07-28T16:40:38+00:00\",\"dateModified\":\"2014-12-07T03:35:07+00:00\",\"author\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc\"},\"breadcrumb\":{\"@id\":\"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jamesonquave.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Re-implementing Optionals using Swift&#8217;s powerful enum type.\"}]},{\"@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":"Re-implementing Optionals using Swift's powerful enum type. - 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\/re-implementing-optionals-using-swifts-powerful-enum-type\/","og_locale":"en_US","og_type":"article","og_title":"Re-implementing Optionals using Swift's powerful enum type. - Jameson Quave","og_description":"This post updated December 6, 2014 to reflect changes in Xcode 6.2 If you&#8217;ve been messing with Swift much lately, you may have noticed that enum&#8217;s do much more than they did in Objective-C, or in most other languages for that matter. In the WWDC videos discussing Swift, one of the presenters mentions that Optionals...","og_url":"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/","og_site_name":"Jameson Quave","article_published_time":"2014-07-28T16:40:38+00:00","article_modified_time":"2014-12-07T03:35:07+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\/re-implementing-optionals-using-swifts-powerful-enum-type\/","url":"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/","name":"Re-implementing Optionals using Swift's powerful enum type. - Jameson Quave","isPartOf":{"@id":"https:\/\/jamesonquave.com\/blog\/#website"},"datePublished":"2014-07-28T16:40:38+00:00","dateModified":"2014-12-07T03:35:07+00:00","author":{"@id":"https:\/\/jamesonquave.com\/blog\/#\/schema\/person\/db6184f355c7f4e3b876d0f228c2fcfc"},"breadcrumb":{"@id":"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jamesonquave.com\/blog\/re-implementing-optionals-using-swifts-powerful-enum-type\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jamesonquave.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Re-implementing Optionals using Swift&#8217;s powerful enum type."}]},{"@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\/1032"}],"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=1032"}],"version-history":[{"count":39,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1032\/revisions"}],"predecessor-version":[{"id":1453,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/posts\/1032\/revisions\/1453"}],"wp:attachment":[{"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/media?parent=1032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/categories?post=1032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jamesonquave.com\/blog\/wp-json\/wp\/v2\/tags?post=1032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}