{"id":314,"date":"2014-06-29T08:58:41","date_gmt":"2014-06-29T14:58:41","guid":{"rendered":"http:\/\/dev.iachieved.it\/iachievedit\/?p=314"},"modified":"2015-12-30T12:34:59","modified_gmt":"2015-12-30T18:34:59","slug":"a-morning-with-swift-optionals","status":"publish","type":"post","link":"https:\/\/dev.iachieved.it\/iachievedit\/a-morning-with-swift-optionals\/","title":{"rendered":"A Morning with Swift Optionals"},"content":{"rendered":"<p>Swift optionals come off as a bit weird.  There, we said it.  Those familiar with Scala, F#, Haskell, or Rust might disagree, but then again, how many people do you know that actually program in Haskell?  And we can guarantee you that 90% of Objective-C programmers out there are not working with these functional programming languages. At any rate, <a href=\"http:\/\/en.wikipedia.org\/wiki\/Option_type\">optional types<\/a> have been introduced to the programming language that will be the flagship for iOS and OS X development in the future.  It&#8217;s time to get on the bandwagon.<\/p>\n<p>At the core optionals are conceptually easy to understand.  An optional type is simply a way of saying that this object here <i>might<\/i> be of type <b>X<\/b>.  Or it might not.  In Swift there are two concrete possibilities (or <i>options<\/i>):  it is either the type it was declared as, or <code>nil<\/code>.  It cannot be some other type.  An illustration:<\/p>\n<pre>\r\nvar currentTemperature:Double?\r\n<\/pre>\n<p>In this example the object to which the <code>currentTemperature<\/code> variable refers can either be a <code>Double<\/code>, or <code>nil<\/code>.  So, let&#8217;s say in our code we use some API to go retrieve the current temperature, and that API has declared a function like this:<\/p>\n<pre>\r\nfunc currentTemperature() -> Double?\r\n<\/pre>\n<p>The <code>Double?<\/code> again signifies that the return value will either be a <code>Double<\/code> or <code>nil<\/code>.  How would you interact with this function?  What if we just did:<\/p>\n<pre>\r\nvar temperature:Double\r\ntemperature = currentTemperature()\r\n<\/pre>\n<p>Swift complains and says &#8220;Value of optional type &#8216;Double?&#8217; not unwrapped; did you mean to use &#8216;!&#8217; or &#8216;?&#8217;?&#8221;  Now don&#8217;t tell us that the first impression of someone with a Ruby, Python, or even Objective-C background wouldn&#8217;t be to look at that and say, huh, what?  Unwrapped?  Like a Chipotle burrito or Snickers bar?  I don&#8217;t get it.<\/p>\n<p>What Swift is saying is &#8220;Hey <i>pal<\/i>, look here.  You presented me with a <code>Double<\/code> variable to capture the return value from a function that may return a <code>Double<\/code> or nothing.  If you really mean it you are going to have to decide whether you want to insist that you will receive a <code>Double<\/code> or you&#8217;ll have to change your variable type.&#8221;  <\/p>\n<p>The first option, using <code>!<\/code>, forces what is known as <i>unwrapping<\/i>, which we liken to casting (but it&#8217;s not really).  It&#8217;s sort of like a declaration that &#8220;we know this a <code>Double<\/code> so use it as one.&#8221;  If it isn&#8217;t actually a <code>Double<\/code> and is truly <code>nil<\/code> you&#8217;re going to get a crash.  Which is actually good if you think about it&#8230; we want errors in logic to crash and burn so we can catch them before we ship our software.   <\/p>\n<p>Typically however you would not code by throwing exclamation marks around (well, sometimes we do if we&#8217;re chasing down an elusive bug).  In practice we&#8217;ve found ourself only using <code>!<\/code> when the application logic is (supposedly) guaranteeing a certain condition, but we prefer the <i>defensive programming<\/i> approach which substitutes <a href=\"http:\/\/en.wikipedia.org\/wiki\/Trust,_but_verify\">&#8220;trust but verify&#8221;<\/a> with &#8220;verify&#8221;.  Swift provides a syntactical construct called <i>optional binding<\/i> that is done like this:<\/p>\n<pre>\r\nif let temperature = currentTemperature() {\r\n  println(\"The temperature is \\(temperature)\")\r\n} else {\r\n  println(\"Unable to obtain current temperature\")\r\n}\r\n<\/pre>\n<p>This is logically equivalent to the following Objective-C code:<\/p>\n<pre>\r\nNSNumber* temperature = [Weather currentTemperature];\r\nif (temperature != nil) {\r\n} else {\r\n}\r\n<\/pre>\n<p>Just keep in mind that a Swift <code>nil<\/code> is not the same as Objective-C&#8217;s <code>nil<\/code>.  Quoting Apple, &#8220;Swift&#8217;s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer\u2014it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.&#8221;<\/p>\n<p>In working with Swift we&#8217;ve found that deferred initialization of object members require you declare them as optional types.  For example:<\/p>\n<pre>\r\nclass Circle {\r\n  \r\n  var radius:Double\r\n  \r\n  init() {\r\n  }\r\n  \r\n}\r\n<\/pre>\n<p>The Swift compiler responds, <code>error: property 'self.radius' not initialized<\/code>.  Now it might not make much sense to have a <code>Circle<\/code> with no radius, but let&#8217;s use our weather example.  We <i>could<\/i> reasonably have <i>nothing<\/i> for our temperature.  Zero as a value won&#8217;t suffice to signify such a situation (alliteration is fun), nor will negative values.  We really do want to be able to declare a variable that could have no temperature.  Here we have created a <code>Weather<\/code> class that has a temperature of type <code>Double?<\/code>.  This allows those obtaining the temperature to understand that it <i>might<\/i> be undefined.<\/p>\n<pre>\r\nclass Weather {\r\n  \r\n  var temperature:Double?\r\n  \r\n  init() {\r\n  }\r\n  \r\n  func currentTemperature() -> Double? {\r\n    return temperature\r\n  }\r\n  \r\n}\r\n\r\nvar weather = Weather()\r\n\r\nif let temperature = weather.currentTemperature() {\r\n  println(\"The current temperature is \\(temperature)\")\r\n} else {\r\n  println(\"Could not obtain temperature\")\r\n}\r\n<\/pre>\n<p>Before we wrap up this little exposition on Swift optionals, let us say this:  you will be well served by spending time with Swift optionals and what unwrapping is and what the <code>!<\/code> and <code>?<\/code> symbols mean.  Our time with iOS 8 and Swift has shown that usage of optionals is significant and that failure to understand them will be a hindrance.  And we haven&#8217;t even done a deep-dive on <a href=\"https:\/\/developer.apple.com\/library\/prerelease\/mac\/documentation\/Swift\/Conceptual\/Swift_Programming_Language\/OptionalChaining.html\">optional chaining<\/a> (next post perhaps), but it too will be a significant part of iOS and OS X programming.  <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Swift optionals come off as a bit weird. There, we said it. Those familiar with Scala, F#, Haskell, or Rust might disagree, but then again, how many people do you know that actually program in Haskell? And we can guarantee you that 90% of Objective-C programmers out there are not working with these functional programming [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-314","post","type-post","status-publish","format-standard","hentry","category-swift"],"_links":{"self":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/314"}],"collection":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/comments?post=314"}],"version-history":[{"count":23,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/314\/revisions"}],"predecessor-version":[{"id":2371,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/314\/revisions\/2371"}],"wp:attachment":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media?parent=314"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/categories?post=314"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/tags?post=314"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}