{"id":8896,"date":"2020-05-08T09:05:47","date_gmt":"2020-05-08T15:05:47","guid":{"rendered":"https:\/\/www.richimages.net\/?p=8896"},"modified":"2020-05-15T09:33:55","modified_gmt":"2020-05-15T15:33:55","slug":"8896","status":"publish","type":"post","link":"https:\/\/richimages.net\/?p=8896","title":{"rendered":"Why I like Swift"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Part 1.  Optionals<\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>BLUF:<\/strong><\/h4>\n\n\n\n<p>Optionals are unique variables types, chosen because they can handle particular situations with greater accuracy. They can convey: (1)\u00a0<em>there is a value for this variable (and, here it is)<\/em>, or, (2)\u00a0<em>we have a situation where it doesn&#8217;t make since for this variable to have a value &#8211; therefore, this variable doesn\u2019t have a value.<\/em><\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Details<\/strong><\/h4>\n\n\n\n<p>For any type in Swift, (String, Int, Float, etc.), an optional variable is declared by appending a\u00a0<strong>?<\/strong>\u00a0onto the end of the type. <\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var anOptionalString: String? = \u201cmy optional string\u201d\nvar anOptionalInt: Int?\n<\/pre>\n\n\n\n<p>The first line can be read as:  <em>declare a variable, anOptionalString, of type Optional String and assign it the value \u201cmy optional string\u201d.<\/em> On the second line, no assignment is made; we let <strong>anOptionalInt<\/strong> default to the value of <strong>nil<\/strong>. Optionals can be assigned <strong>nil<\/strong> at any time, even after it has been assigned a value.  <\/p>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"true\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print( \u201c \\(anOptionalString) \u201c)\n\/\/ prints:\n\/\/ Optional(\u201cmy optional string\u201d) \n\nprint(\u201c \\(anOptionalString!) \u201c) \/\/ force unwrap value using !\n\/\/ prints:\n\/\/ my optional string<\/pre>\n\n\n\n<p>Here, we attempt to print <strong>anOptionalString<\/strong>, but it doesn\u2019t print the pure string we expect. Its value needs to be <em>unwrapped<\/em>. On line 5 we force unwrap the value with a exclamation mark at the end of the variable. It works, but unwrapping an optional by force is not a good practice; if the optional has no value, the program will crash. We\u2019ll look at better ways to unwrap optional values in a bit.  <\/p>\n\n\n\n<p>Behind the scenes, an optional is implemented as <em>a two-cased enum<\/em>. The two cases are <strong>some<\/strong> and <strong>none<\/strong>. In the case of <strong>some<\/strong>, the enum holds &#8220;<em>associated data<\/em>&#8221; that matches the enum&#8217;s <em>backed-data-type<\/em>; <strong>none<\/strong> cases return <strong>nil<\/strong>. Optionals are so common in Swift, there are several forms of syntactic sugar that safely check for set cases, and retrieve associated data in the same construct. For example:<\/p>\n\n\n\n<h6 class=\"wp-block-heading\">Nil coalescing operator: ??<\/h6>\n\n\n\n<div class=\"wp-block-group\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"true\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var pbsNodeTypeString: String? = \":bigmem=1\" \nlet blankString = \"\"\n\/\/ var declares a variable, let declares a constant\n\nprint( \"select=1:ncpus=24:mpiprocs=24\\(pbsNodeTypeString ??  blankString)\" \n\/\/ prints select=1:ncpus=24:mpiprocs=24:bigmem=1 \n\n\/\/ set up for pbs SELECT statement for standard job ...\npbsGpuNodeString = nil \n\nprint( \"select=1:ncpus=24:mpiprocs=24\\(pbsNodeTypeString ?? blankString)\" \n\/\/ prints select=1:ncpus=24:mpiprocs=24\n\n<\/pre>\n<\/div><\/div>\n\n\n\n<p>The nil coalescing operator,\u00a0used within the print statements on lines 5 and 11, says:\u00a0<em>if the optional to the left has a value, unwrap it and use it here, else, use the value to the right in this place.\u00a0<\/em><\/p>\n\n\n\n<p>Of course, we could have accomplished this with a regular String, and simply set it to hold a blank string for a standard pbs job. We&#8217;ll look at a better example ahead.\u00a0<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Advantages of Optionals<\/strong><\/h4>\n\n\n\n<p>Optionals are able to hold more information than a simple data value. Since they can be\u00a0<em>set<\/em> or <em>unset<\/em>, they can imply a boolean value, answering a <strong>yes\/no<\/strong> question.  Optional variables can say:\u00a0<em>\u201cYes, there is a value here, and here\u2019s my associated data\u201d<\/em>, or <em>&#8220;No, there&#8217;s no value here<\/em>&#8220;.\u00a0 The question it answers has to do with the variable.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">struct HistoricalPerson {\n   var name: String\n   var birthDate: String\n   var deathDate: String?\n   .\n   .\n   .\n}\n<\/pre>\n\n\n\n<p>Consider the variables <strong>birthDate<\/strong> and <strong>deathDate<\/strong> in the struct above. Anyone who is a <strong>HistoricalPerson<\/strong> has a <strong>birthDate<\/strong>, so that variable can be a normal String. But not every <strong>HistoricalPerson<\/strong> has a <strong>deathDate<\/strong> (yet). It&#8217;s more accurate to let that variable be an Optional String. As an optional, <strong>deathDate <\/strong>is able to declare:\u00a0<em>\u201cyes, there is a value, and this is it\u201d<\/em>\u00a0or else\u00a0<em>\u201cno, there is no value here\u00a0&#8211; a value in this case would not make sense &#8211; as this HistoricalPerson is still living.\u201d<\/em><\/p>\n\n\n\n<p>To use the True\/False nature of Optionals, Swift provides the syntactic sugar of an&nbsp;<strong>if let<\/strong>&nbsp;statement.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"false\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var somePastPOTUS = HistoricalPerson()\n\/\/ set the struct properties for the historical POTUS\n\nif let date = somePastPOTUS.deathDate {\n       \/\/ code block if date receives an associated value\n       print(\"death date was \\(date)\")\n} else {\n       \/\/ code block when somePastPOTUS.deathDate is nil\n       print(\" \\(somePastPOTUS.name) is still living\") \n}\n<\/pre>\n\n\n\n<p>The&nbsp;<strong>if let<\/strong>&nbsp;construct above, can be read as:<\/p>\n\n\n\n<p><strong>If<\/strong>&nbsp;(we can)&nbsp;<strong>let date equal<\/strong>&nbsp;the associated data of the Optional String variable&nbsp;<strong>somePastPOTUS.deathDate<\/strong>, then execute the first block of code, with&nbsp;<strong>date<\/strong>&nbsp;set to that value &#8211;&nbsp;<strong>else<\/strong>&nbsp;execute the second block of code with no assignment to the&nbsp;<strong>date<\/strong>&nbsp;variable.&nbsp;<\/p>\n\n\n\n<p><strong>Other Syntactic Sugar for Optionals<\/strong><\/p>\n\n\n\n<p><strong>Guard statement.<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"swift\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\nguard let unwrappedDate = somePastPOTUS.deathDate else {\n      \/\/ code block to clean up, and transfer program control\n      return\n}\n\/\/ code resumes pending guard statement executed normally <\/pre>\n\n\n\n<p>A <strong>guard<\/strong> statement ensures the line will execute properly, or <strong>else<\/strong> will enter a code block to perform corrective actions and finally will transfer program control with either a <strong>return, break, continue<\/strong> or <strong>throw<\/strong> statement. Often a simple <strong>return<\/strong> statement is seen as the entire code block. <\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>The Argument for Optionals<\/strong><\/h4>\n\n\n\n<p>Optionals eliminate many runtime errors. For Example, when requesting a dictionary retrieval with a non-existent key. (Swift dictionaries always return optionals, since this is possible, forcing non-existent keys to be dealt with.)<\/p>\n\n\n\n<p><strong>Optionals Can Solve Ambiguous Meaning<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Suppose you get a return of -1 from a function called: <strong>getGreatestIntInList( list )<\/strong>. Is -1 the greatest value in the list? Or was this an empty list ?  Changing the function to return an optional Int? would solve this problem. <\/li><li>Suppose you get a return of 0 from a function called: <strong>getIndexOfFirstSubStringInString(subString, String)<\/strong>. Does that mean the substring occurs immediately in the String, or that no subString exists in the String? Using an optional Int? return value would solve this problem. <\/li><\/ul>\n\n\n\n<p><strong>Solves Doesn&#8217;t-Exists Values<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>var <strong>spouseName<\/strong>: <strong>String?<\/strong>\u00a0<em>\/\/ handles not-married cases <\/em><\/li><li>var <strong>flightTimeFromCityAToCityB<\/strong>: <strong>Int?<\/strong>\u00a0<em>\/\/ handles cases where no single flight exists from City A to City B<\/em><\/li><li>var <strong>pbsRequiredQueueNameForQsubType<\/strong>\u00a0: <strong>String?<\/strong> <em>\/\/ handles cases when the QsubType is defined instead by a pbsQsubTypeString appended onto the end of the SELECT statement<\/em><\/li><li>var <strong>pbsQsubTypeString<\/strong>: <strong>String?<\/strong> \u00a0<em>\/\/ handles cases when the QsubType is defined instead by establishing a dedicated queue for these jobs to run in.<\/em><\/li><\/ul>\n\n\n\n<p><strong>Simplifies logic<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>var <strong>valueOfOneAndOnlyFaceUpCard<\/strong>: <strong>CardRank?<\/strong>\u00a0<em>\/\/ A neat way to know that the condition-of-interest is met, and the card rank when that condition is met.<\/em> We&#8217;re able to directly code for that situation directly from inspecting the variable.  Also, if we find no cards are face-up, or more than one card is face-up, we can set this variable to <strong>nil<\/strong> to better describe the state of the game.<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Recap<\/strong><\/h4>\n\n\n\n<p>Can we survive without Optionals in a programming language? Of course we can. Still, there are advantages of having Optional types that Swift brings to the table.<\/p>\n\n\n\n<p>Optionals remind us that there are times when the value of <strong><em>nothing<\/em><\/strong> can be an appropriate and valid.  Some programming languages touch on this, or have ambiguous workarounds, but Swift directly supports this concept through Optional data types. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Part 1. Optionals BLUF: Optionals are unique variables types, chosen because they can handle particular situations with greater accuracy. They can convey: (1)\u00a0there is a value for this variable (and,&hellip; <\/p>\n","protected":false},"author":3,"featured_media":9040,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[276],"tags":[275,274],"class_list":["post-8896","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-swift","tag-optionals","tag-swift"],"_links":{"self":[{"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/posts\/8896","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/richimages.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=8896"}],"version-history":[{"count":5,"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/posts\/8896\/revisions"}],"predecessor-version":[{"id":9170,"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/posts\/8896\/revisions\/9170"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/richimages.net\/index.php?rest_route=\/wp\/v2\/media\/9040"}],"wp:attachment":[{"href":"https:\/\/richimages.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=8896"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/richimages.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=8896"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/richimages.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=8896"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}