{"id":700,"date":"2014-06-25T11:54:35","date_gmt":"2014-06-25T15:54:35","guid":{"rendered":"http:\/\/www.peteonsoftware.com\/?p=700"},"modified":"2024-03-02T16:08:23","modified_gmt":"2024-03-02T21:08:23","slug":"swift-control-structures","status":"publish","type":"post","link":"https:\/\/www.peteonsoftware.com\/index.php\/2014\/06\/25\/swift-control-structures\/","title":{"rendered":"Swift &#8211; Control Structures"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/swift.jpg\" alt=\"Apple's Swift Language\" title=\"Apple's Swift Language\" style=\"float:left; margin:.5em;\">In the <a href=\"https:\/\/www.peteonsoftware.com\/index.php\/2014\/06\/24\/swift-collections-and-iterations\/\">previous post<\/a> in this Swift series, we looked at collections and iterating over those collections.  In this post, I want to take a look at control structures.  How does Swift allow you to make decisions in your code?<\/p>\n<p>Much the same way that the for loop looked very familiar to us, only lacking parentheses, the if statement behaves the same way.  As you&#8217;d expect, the following code outputs &#8220;You cannot register to vote&#8221;.<\/p>\n<pre>\r\nlet age = 7;\r\n\r\nif age &gt;= 18 {\r\n    println(\"You can register to vote\")\r\n} else {\r\n    println(\"You cannot register to vote\")\r\n}\r\n<\/pre>\n<p>For a predefined number of &#8220;if statements&#8221;, many developers like to use a switch statement.  Traditionally, in c-based languages, you would switch on a variable and then provide a case for each of your possibilities.  Here is an example of a Swift Switch statement that would output &#8220;Back to the Grind&#8221; to the console.<\/p>\n<pre>\r\nlet dayOfWeek = \"Monday\"\r\n\r\nswitch dayOfWeek {\r\n    case \"Saturday\", \"Sunday\":\r\n        println(\"Party!\")\r\n    case \"Monday\":\r\n        println(\"Back to the Grind\")\r\n    case \"Wednesday\":\r\n        println(\"Hump DAY\")\r\n    default:\r\n        println(\"Just another day\")\r\n}\r\n<\/pre>\n<p>There are several interesting things to point out here.  The first is that you don&#8217;t need break statements after each case.  The reason for break statements is because when you want to have the same action for multiples cases, you would stack them without a break.  In Swift, you just make a comma-separated list between the case keyword and the colon, as I did for Saturday and Sunday above.  To me, this makes a lot of sense and is much cleaner.<\/p>\n<p>If you omit the default option, though, you get an interesting error that says <em>&#8220;error: switch must be exhaustive, consider adding a default clause&#8221;<\/em>.  That means that you must account for every possibility in your switch statement code.  But how smart is it?  Consider this example:<\/p>\n<pre>\r\nlet guess = 7\r\n\r\nswitch guess {\r\n    case 0:\r\n        println(\"Your guess is 0\")\r\n    case let x where x &gt; 0:\r\n        println(\"Your guess is positive\")\r\n    case let x where x &lt; 0:\r\n        println(\"Your guess is negative\")\r\n}\r\n<\/pre>\n<p>This code covers every possible value for x and therefore is logically exhaustive.  However, as it is, it also causes the <em>&#8220;error: switch must be exhaustive, consider adding a default clause&#8221;<\/em> error to appear.  I have to change the code to this for it to work:<\/p>\n<pre>\r\nlet guess = 7\r\n\r\nswitch guess {\r\n    case 0:\r\n        println(\"Your guess is 0\")\r\n    case let x where x &gt; 0:\r\n        println(\"Your guess is positive\")\r\n    case let x where x &lt; 0:\r\n        println(\"Your guess is negative\")\r\n    default:\r\n        println(\"This will never ever get called\")\r\n}\r\n<\/pre>\n<p>I also added another interesting feature of Swift&#8217;s Switch statement and that is the ability to make a local copy of the variable and then use that to make any comparison rather than to compare only against a constant.    That is another very powerful feature.<\/p>\n<p>The While keyword is another way that we can control program execution.  As is our pattern, this looks like a standard c-style while loop, minus the parentheses.  <\/p>\n<pre>\r\nvar number = -100\r\n\r\nwhile number &lt; 0 {\r\n    println(number)\r\n    number += 10\r\n}\r\n<\/pre>\n<p>This gives us the following output:<br \/>\n<img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/SwiftWhileLoop.png\" alt=\"Swift While Loop\" title=\"Swift While Loop\" \/><\/p>\n<p>But, what if our original value was 10, like this?  Our code wouldn&#8217;t do anything.<\/p>\n<pre>\r\nvar number = 10\r\n\r\nwhile number &lt; 0 {\r\n    println(number)\r\n    number += 10\r\n}\r\n<\/pre>\n<p>If we want to ensure that our code is executed at least once, we can employ the do-while structure, which looks like this:<\/p>\n<pre>\r\nvar number = 10\r\n\r\ndo {\r\n    println(number)\r\n    number += 10\r\n} while number &lt; 0\r\n<\/pre>\n<p>Now, we execute at least once before we see that we don&#8217;t meet the conditions.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/SwiftDoWhile.png\" alt=\"Swift Do While Loop\" title=\"Swift Do While Loop\" \/><\/p>\n<p>That only leaves us one last basic control structure and that is the standard for loop.  I have the option of doing the c-style parentheses-free version.<\/p>\n<pre>\r\nfor var i = 1; i &lt;= 10; i++ {\r\n    println(i)\r\n}\r\n<\/pre>\n<p>If I&#8217;m doing a range, though, I can also declare that range in a Ruby-ish way.<\/p>\n<pre>\r\n\/\/ ..&lt; does not include the upper bound\r\nfor i in 1..&lt;10 {\r\n    println(i)\r\n}\r\n\r\n\/\/ ... does include the upper bound\r\nfor i in 1...10 {\r\n    println(i)\r\n}\r\n<\/pre>\n<p><em>UPDATE 7\/16\/2014: In Xcode 6 beta 3, the Swift language was changed and the non-inclusive range was changed from the &#8220;..&#8221; operator to &#8220;..<\" for readability reasons.  If you are on Beta 2 or less, use ..<\/em><\/p>\n<p>That&#8217;s it for control structures.  Next time, we&#8217;ll take it up a notch and take a look at declaring and calling functions in Swift.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous post in this Swift series, we looked at collections and iterating over those collections. In this post, I want to take a look at control structures. How does Swift allow you to &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[132,75,77],"tags":[78,129,131],"class_list":["post-700","post","type-post","status-publish","format-standard","hentry","category-intro-to-swift","category-ios","category-swift","tag-intro-to-swift","tag-ios","tag-swift"],"_links":{"self":[{"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/posts\/700","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/comments?post=700"}],"version-history":[{"count":0,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/posts\/700\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/media?parent=700"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/categories?post=700"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/tags?post=700"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}