{"id":324,"date":"2014-10-05T13:00:15","date_gmt":"2014-10-05T13:00:15","guid":{"rendered":"http:\/\/www.yeahbutisitswift.com\/?p=324"},"modified":"2015-05-14T20:01:48","modified_gmt":"2015-05-14T20:01:48","slug":"quick-start-guide-to-swift-part-2","status":"publish","type":"post","link":"http:\/\/www.yeahbutisitswift.com\/?p=324","title":{"rendered":"Quick Start Guide to Swift: Part 2"},"content":{"rendered":"<p>Welcome to the second tutorial in this quick start guide to Swift. We&#8217;ll cover some of the concepts from the <a href=\"?p=522\" target=\"_blank\">first part<\/a> in more detail while also introducing more language features.<\/p>\n<h3>What you will learn&#8230;<\/h3>\n<ul>\n<li>More detail regarding strings<\/li>\n<li>How to work with arrays and dictionaries<\/li>\n<li>Control flow with while loops and the switch statement<\/li>\n<li>How to work with enumerations<\/li>\n<\/ul>\n<h3>What you should know&#8230;<\/h3>\n<ul>\n<li>A familiarity with at least one programming language<\/li>\n<li>The basics of the Swift programming language from <a href=\"?p=522\" target=\"_blank\">part one<\/a><\/li>\n<\/ul>\n<p>The primary focus of part two will be strings, collection types, control flow, and enumerations. We briefly looked at strings in <a href=\"?p=522\" target=\"_blank\">part one<\/a> but will spend more time with them here. We&#8217;ll also re-visit control flow, taking the time to examine <code>while<\/code> loops, <code>do-while<\/code> loops, and Swift&#8217;s powerful <code>switch<\/code> statement. You may have noticed that arrays weren&#8217;t covered in <a href=\"?p=522\" target=\"_blank\">part one<\/a>. We&#8217;ll make up for that here and also focus on Swift&#8217;s other collection type: dictionaries. Finally we&#8217;ll round off part two by covering enumerations.<\/p>\n<p>ECMAScript developers following this series will discover that most of what is covered here isn&#8217;t that dissimilar to the features found in languages such as JavaScript and ActionScript. Enumerations being really the only exception for some of you. For those from a C programming background, everything will feel familiar, although you may be surprised at the additional power and flexibility that Swift brings to many of these features.<\/p>\n<p>As stated previously, everything covered in this series of tutorials can also be found in Apple\u2019s own official guide to the Swift programming language. The intention here however is to focus on the elements of the language that are required to get newcomers up and running as quickly as possible. If you have the time and want the full detail then I highly recommend you head straight over to Apple\u2019s <a href=\"https:\/\/developer.apple.com\/library\/ios\/documentation\/Swift\/Conceptual\/Swift_Programming_Language\/TheBasics.html#\/\/apple_ref\/doc\/uid\/TP40014097-CH5-XID_454\" target=\"_blank\">Swift Programming Language Guide<\/a> instead.<\/p>\n<p><!--more--><\/p>\n<h2>Getting Started<\/h2>\n<p>If you haven\u2019t worked your way through the <a href=\"?p=522\" target=\"_blank\">first tutorial<\/a> in the series then I recommend you start from there.<\/p>\n<p>You should also consider installing <a href=\"https:\/\/developer.apple.com\/xcode\/downloads\/\" target=\"_blank\">Xcode 6<\/a> and creating a playground to try out his tutorial&#8217;s various code examples. Detail regarding that can be found in the <a href=\"?p=522\" target=\"_blank\">first tutorial<\/a>.<\/p>\n<h2>More on Strings<\/h2>\n<p>We briefly looked at strings in the <a href=\"?p=522\" target=\"_blank\">first tutorial<\/a>. Let&#8217;s revisit them and get some more detail.<\/p>\n<p>The <code>String<\/code> type represents a collection of ordered values of type <code>Character<\/code>. Swift\u2019s <code>String<\/code> and <code>Character<\/code> types are fully Unicode-compliant. As discussed previously, a string literal can be used to initialise your variables and constants:<\/p>\n<p><codeswift>let jedi = &quot;Luke Skywalker&quot;<\/codeswift><\/p>\n<p>It&#8217;s also possible to create a string that is initially empty:<\/p>\n<p><codeswift>var playerName = &quot;&quot;<\/codeswift><\/p>\n<p>You can also check whether a string is empty:<\/p>\n<p><codeswift>if playerName.isEmpty {<br \/>\n&nbsp;&nbsp;playerName = &quot;anonymous&quot;<br \/>\n}<\/codeswift><\/p>\n<p>The &#8220;equal to&#8221; operator (<code>==<\/code>) is used to determine if two strings are equal:<\/p>\n<p><codeswift>let person1 = &quot;Christopher&quot;<br \/>\nlet person2 = &quot;Christopher&quot;<br \/>\nif person1 == person2 {<br \/>\n&nbsp;&nbsp;println(&quot;Both people share the same name.&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>The addition (<code>+<\/code>) operator can be used to concatenate strings:<\/p>\n<p><codeswift>var forename = &quot;Luke&quot;<br \/>\nvar surname = &quot;Skywalker&quot;<br \/>\nvar name = forename + &quot; &quot; + surname<\/codeswift><\/p>\n<p>Only string variables can be changed after they are initialised. Once a string constant has been set, it cannot be altered. The following example will result in a compile-time error:<\/p>\n<p><codeswift>let name = &quot;Anakin Skywalker&quot;<br \/>\nname = &quot;Darth Vader&quot;<\/codeswift><\/p>\n<h3>Characters<\/h3>\n<p>As stated, a string is an ordered collection of characters. You can access each of a string&#8217;s characters with a <code>for-in<\/code> loop. Here&#8217;s an example:<\/p>\n<p><codeswift>let sith = &quot;Darth&quot;<br \/>\nfor c in sith {<br \/>\n&nbsp;&nbsp;println(c)<br \/>\n}<\/codeswift><\/p>\n<p>This will result in the following being output:<\/p>\n<p><codeswift>D<br \/>\na<br \/>\nr<br \/>\nt<br \/>\nh<\/codeswift><\/p>\n<div class=\"zilla-alert white\"> In order to see the results of a loop within your playground you&#8217;ll need to take advantage of the timeline assistant. To do this, look in the sidebar, directly along from your loop&#8217;s <code>println()<\/code> call. You should see the text <code>(5 times)<\/code> and an icon of a dot to the right of that.<\/p>\n<div align=\"center\" style=\"margin-bottom:20px;\"><a href=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/timeline-assistant.png\"><img loading=\"lazy\" decoding=\"async\" style=\"width:440px;\" src=\"http:\/\/www.yeahbutisitswift.com\/wp-content\/uploads\/2014\/08\/timeline-assistant-1024x791.png\" alt=\"timeline-assistant\" width=\"750\" height=\"579\" \/><\/a><\/div>\n<p>If you click that icon, the timeline assistant pane will open and you&#8217;ll be able to see the result from each iteration of your loop. <\/div>\n<p>In the code example above, the <code>c<\/code> variable will hold a single character at any one time and is therefore of type <code>Character<\/code>.<\/p>\n<p>As with strings, the &#8220;equal to&#8221; operator (<code>==<\/code>) is used to check if two characters are equal:<\/p>\n<p><codeswift>let character1: Character = &quot;c&quot;<br \/>\nlet character2: Character = &quot;c&quot;<br \/>\nif character1 == character2 {<br \/>\n&nbsp;&nbsp;println(&quot;Both characters are the same.&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Notice that the <code>Character<\/code> type had to be explicitly declared to prevent both variables from being inferred as <code>String<\/code> types. There is no single-quote syntax for character literals in Swift.<\/p>\n<p>It&#8217;s not possible to check the equality of a <code>String<\/code> against a <code>Character<\/code> without first converting the character to a <code>String<\/code> type. Here&#8217;s an example:<\/p>\n<p><codeswift>let myCharacter: Character = &quot;c&quot;<br \/>\nlet myString = &quot;c&quot;<br \/>\nif String(myCharacter) == myString {<br \/>\n&nbsp;&nbsp;println(&quot;Both characters are the same.&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>You can append a <code>Character<\/code> value to a <code>String<\/code> with the <code>append()<\/code> method. Here&#8217;s an example:<\/p>\n<p><codeswift>var greeting = &quot;Hullo&quot;<br \/>\nlet exclamationMark: Character = &quot;!&quot;<br \/>\ngreeting.append(exclamationMark)<\/codeswift><\/p>\n<p>You can obtain the number of characters in a string by using the global <code>count()<\/code> function:<\/p>\n<p><codeswift>var jedi = &quot;Luke Skywalker&quot;<br \/>\nvar numberOfCharacters = countElements(jedi)<br \/>\nprintln(numberOfCharacters)<\/codeswift><\/p>\n<p>The above example will output <code>14<\/code>.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> Create two constants. Set the first to hold your forename and the second to hold your surname. Concatenate both constants and hold the result in a variable called <code>fullname<\/code>. Finally check the number of characters stored within your <code>fullname<\/code> variable. If it&#8217;s over 15 characters in length then print <code>The name is too long.<\/code> to the appropriate output. Otherwise, simply print your full name.<\/div><\/div>\n<h3>String Interpolation<\/h3>\n<p>We&#8217;ve already utilised string interpolation when working with the global <code>println()<\/code> function. String interpolation allows you to insert variables, constants, literals, and expressions as placeholders directly within a string. This is done by wrapping each item in parentheses and escaping them with a backslash before the opening parenthesis. Here&#8217;s an example:<\/p>\n<p><codeswift>let name = &quot;Luke Skywalker&quot;<br \/>\nvar kills = 64<br \/>\nlet pointsPerKill = 10<br \/>\nlet message = &quot;\\(name) scored a total of \\(kills * pointsPerKill) points&quot;<\/codeswift><\/p>\n<p>This will result in a <code>message<\/code> variable that contains the string value: <code>Luke Skywalker scored a total of 640 points<\/code>.<\/p>\n<h3>Character Indexing<\/h3>\n<p>The internal Unicode representation of strings in Swift means that random access of a string&#8217;s individual <code>Character<\/code> values via integer indexing is not supported. For example, you may reasonably expect the following to work:<\/p>\n<p><codeswift>let pilot = &quot;Wedge&quot;<br \/>\nlet lastCharacter = pilot[4]<\/codeswift> <\/p>\n<p>Instead you need to query a string for its starting index and then use the global <code>advance()<\/code> function to move to the desired position within the string. Here&#8217;s the previous example rewritten:<\/p>\n<p><codeswift>let pilot = &quot;Wedge&quot;<br \/>\nlet index = advance(pilot.startIndex, 4)<br \/>\nlet lastCharacter = pilot[index]<\/codeswift><\/p>\n<p>This will result in the <code>lastCharacter<\/code> constant being assigned a value of <code>e<\/code>. It&#8217;s important to note that the <code>index<\/code> constant above is not of type <code>Int<\/code>. Instead it&#8217;s a <code>String.Index<\/code> opaque type, which Swift&#8217;s character and range indices are based on.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> Alter the previous experiment&#8217;s code to print out a truncated version of your full name if it&#8217;s over 15 characters in length. The name should end with an ellipsis to indicate that it has been truncated. For example, the name <code>Christopher Caleb<\/code> would be displayed as <code>Christopher Cal...<\/code>.<\/div><\/div>\n<h2>Arrays<\/h2>\n<p>Arrays are one of two collection types supported by Swift (Dictionaries being the other). Each element within a Swift array must be of the same type.<\/p>\n<div class=\"zilla-alert white\">This is different from languages such as JavaScript, ActionScript, and even Objective-C, where each element can be of a different type.<\/div>\n<h3>Initialising Arrays<\/h3>\n<p>An array can be declared and initialised with an array literal. Here&#8217;s an example:<\/p>\n<p><codeswift>var droids: [String] = [&quot;c3p0&quot;, &quot;r2d2&quot;]<\/codeswift><\/p>\n<p>This creates an array that initially contains two strings: &quot;c3p0&quot; and &quot;r2d2&quot;. Of course, thanks to Swift&#8217;s type inference we can actually shorten the above example to:<\/p>\n<p><codeswift>var droids = [&quot;c3p0&quot;, &quot;r2d2&quot;]<\/codeswift><\/p>\n<p>An immutable array can be created by using a constant instead of a variable:<\/p>\n<p><codeswift>let droids = [&quot;c3p0&quot;, &quot;r2d2&quot;]<\/codeswift><\/p>\n<p>In the example above, the array cannot be altered after it&#8217;s initialised. By assigning your array to a variable instead, you&#8217;ll be free to add, remove, or change values stored within it.<\/p>\n<p>You can create an empty array of a specified type with the following:<\/p>\n<p><codeswift>var droids: [String] = []<\/codeswift><\/p>\n<p>Or alternatively by using Swift&#8217;s initializer syntax:<\/p>\n<p><codeswift>var droids = [String]()<\/codeswift><\/p>\n<p>There&#8217;s also an initializer for creating an array of a certain size and populating it with a provided default value. The following creates an array of 100 integers, with each initialised to 64:<\/p>\n<p><codeswift>var myArray = [Int](count: 100, repeatedValue: 64)<\/codeswift> <\/p>\n<h3>Accessing and Modifying an Array<\/h3>\n<p>Swift uses subscript syntax and zero-based indexing to obtain and modify the value of items within an array. Here&#8217;s an example that changes an array&#8217;s 5th item from <code>1500<\/code> to <code>2000<\/code>:<\/p>\n<p><codeswift>var scores = [100, 200, 500, 1000, 1500]<br \/>\nscores[4] = 2000<\/codeswift><\/p>\n<p>The following example obtains the value of the first item within the array:<\/p>\n<p><codeswift>var scores = [100, 200, 500, 1000, 1500]<br \/>\nvar lowestScore = scores[0]<\/codeswift><\/p>\n<p>Subscript syntax can even be used to replace a range of values within an array:<\/p>\n<p><codeswift>var topFriends = [&quot;Bob&quot;, &quot;James&quot;, &quot;Jane&quot;, &quot;Elizabeth&quot;, &quot;Amanda&quot;]<br \/>\ntopFriends[0&#46;&#46;&#46;2] = [&quot;Christopher&quot;, &quot;Alan&quot;, &quot;Freddy&quot;]<\/codeswift><\/p>\n<p>This will replace the first three strings within the <code>topFriends<\/code> array with &#8220;Christopher&#8221;, &#8220;Alan&#8221;, and &#8220;Freddy&#8221;.<\/p>\n<p>You can add a new item to the end of an array with the <code>append()<\/code> method:<\/p>\n<p><codeswift>var droids = [&quot;c3p0&quot;, &quot;r2d2&quot;]<br \/>\ndroids.append(&quot;r5d5&quot;)<br \/>\nprintln(droids)<\/codeswift><\/p>\n<p>The code example above will output <code>[c3p0, r2d2, r5d5]<\/code>.<\/p>\n<p>It&#8217;s also possible to append an array of compatible values to an existing array. This is done with the addition assignment operator (<code>+=<\/code>):<\/p>\n<p><codeswift>var droids = [&quot;c3p0&quot;, &quot;r2d2&quot;]<br \/>\ndroids += [&quot;r5d5&quot;, &quot;ig88&quot;, &quot;tc14&quot;]<br \/>\nprintln(droids)<\/codeswift><\/p>\n<p>The example above will print <code>[c3p0, r2d2, r5d5, ig88, tc14]<\/code> to the appropriate output.<\/p>\n<p>Swift provides an <code>insert(atIndex:)<\/code> method, which inserts an item at the specified index:<\/p>\n<p><codeswift>var bestScores = [10, 50, 100, 500]<br \/>\nbestScores.insert(150, atIndex:3)<br \/>\nprintln(bestScores)<\/codeswift><\/p>\n<p>This will insert a value of <code>150<\/code> immediately after <code>100<\/code> in the array. The final output will be: <code>[10, 50, 100, 150, 500]<\/code>.<\/p>\n<p>You can remove an item at a specific index with the <code>removeAtIndex()<\/code> method:<\/p>\n<p><codeswift>var bestScores = [10, 50, 100, 500]<br \/>\nbestScores.removeAtIndex(1)<br \/>\nprintln(bestScores)<\/codeswift><\/p>\n<p>This will remove the second item from the array and print the following: <code>[10, 100, 500]<\/code>.<\/p>\n<p>You can obtain the number of items in an array via its <code>count<\/code> property:<\/p>\n<p><codeswift>var jedi = [&quot;Skywalker&quot;, &quot;Kenobi&quot;, &quot;Yoda&quot;, &quot;Windu&quot;]<br \/>\nlet numberOfJedi = jedi.count<\/codeswift><\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\"> Write a program that takes an array of integers and sorts them in ascending order. The sorted list should be printed to the appropriate output. For example, if you were to start off by initialising a variable that held the following values: 20, 40, 10, 5, 200, 145, 5. Then your program should display those values in the following order as its final result: 5, 5, 10, 20, 40, 145, 200.<\/div><\/div>\n<h3>Accessing Outside An Array&#8217;s Bounds<\/h3>\n<p>A runtime error is triggered if you attempt to obtain or set a value for an index that is outside an array&#8217;s bounds. For example:<\/p>\n<p><codeswift>var jedi = [&quot;Skywalker&quot;, &quot;Kenobi&quot;, &quot;Yoda&quot;, &quot;Windu&quot;]<br \/>\nlet name = jedi[64]<br \/>\nprintln(&quot;Name: \\(name)&quot;)<\/codeswift> <\/p>\n<p>This will result in a runtime error since we&#8217;re trying to access the 65th string within an array that only contains four values.<\/p>\n<p>Before accessing or modifying a value within an array you should use its <code>count<\/code> property to determine whether the index position you are using is valid:<\/p>\n<p><codeswift>var jedi = [&quot;Skywalker&quot;, &quot;Kenobi&quot;, &quot;Yoda&quot;, &quot;Windu&quot;]<br \/>\nvar index = 64<br \/>\nif index < jedi.count {\n&nbsp;&nbsp;let name = jedi[index]\n&nbsp;&nbsp;println(&quot;Name: \\(name)&quot;)\n}<\/codeswift><\/p>\n<p>The example above avoids the risk of a runtime error. It&#8217;s also worth remembering that array indexes are zero-based in Swift. You should take that into account when using an array&#8217;s size to determine if an index position is within bounds.<\/p>\n<h3>Iterating Over an Array<\/h3>\n<p>You can use a <code>for-in<\/code> loop to iterate over an array:<\/p>\n<p><codeswift>var jedi = [&quot;Skywalker&quot;, &quot;Kenobi&quot;, &quot;Yoda&quot;, &quot;Windu&quot;]<br \/>\nfor name in jedi {<br \/>\n&nbsp;println(name)<br \/>\n}<\/codeswift><\/p>\n<p>The code snippet above will print the following to the appropriate output:<\/p>\n<p><codeswift>Skywalker<br \/>\nKenobi<br \/>\nYoda<br \/>\nWindu<\/codeswift><\/p>\n<p>You can also take advantage of Swift&#8217;s global <code>enumerate()<\/code> function to extract the value and index position of each item into a tuple. Here&#8217;s how:<\/p>\n<p><codeswift>var jedi = [&quot;Skywalker&quot;, &quot;Kenobi&quot;, &quot;Yoda&quot;, &quot;Windu&quot;]<br \/>\nfor (index, name) in enumerate(jedi) {<br \/>\n&nbsp;&nbsp;println(&quot;\\(index): \\(name)&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>This will result in the following being output:<\/p>\n<p><codeswift>0: Skywalker<br \/>\n1: Kenobi<br \/>\n2: Yoda<br \/>\n3: Windu<\/codeswift><\/p>\n<h2>Dictionaries<\/h2>\n<p>Unlike arrays, dictionaries do not store items in a specified order. Instead, each item added to a dictionary is associated with a unique key, which acts as an identifier for that item. All items added to a dictionary must be of the same type. The same is true for the unique keys you use also.<\/p>\n<div class=\"zilla-alert white\">When working with dictionaries in Swift, you have to be specific about the type you&#8217;ll use for your keys, and the type you&#8217;ll use for your values. This is different from languages such as JavaScript, ActionScript 3, and even Objective-C, where you can use a different type for each key and each value if you wish.<\/div>\n<p>Let&#8217;s look at a simple example:<\/p>\n<p><codeswift>var scores: [String: Int] = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<\/codeswift><\/p>\n<p>We have a dictionary of player scores. Each player&#8217;s name is used as a key, and there is a score associated with each key. The keys are of type <code>String<\/code> and the values are all of type <code>Int<\/code>. In other words, we have declared a dictionary that has a type of <code>[String: Int]<\/code>.<\/p>\n<p>Since we initialised our <code>scores<\/code> dictionary with a literal we can let Swift infer the dictionary&#8217;s type for us. So we can shorten our original example to this:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<\/codeswift><\/p>\n<p>An immutable dictionary can be created by using a constant instead of a variable:<\/p>\n<p><codeswift>let scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<\/codeswift><\/p>\n<p>You can create an empty dictionary of a specified type with the following:<\/p>\n<p><codeswift>var scores: [String: Int] = [:]<\/codeswift><\/p>\n<p>Or alternatively by using Swift&#8217;s initializer syntax:<\/p>\n<p><codeswift>var scores = [String: Int]()<\/codeswift><\/p>\n<h3>Accessing and Modifying a Dictionary<\/h3>\n<p>Subscript syntax is used to access or modify an existing value within a dictionary. Here&#8217;s an example of a value being modified:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nscores[&quot;Freddy&quot;] = 20000<\/codeswift><\/p>\n<p>A little more effort is required to access a value. It&#8217;s possible that the key you use with your subscript may not actually have an associated value within the dictionary:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nlet score = scores[&quot;Bob&quot;]<\/codeswift><\/p>\n<p>As you can see from the example above, the key <code>Bob<\/code> doesn&#8217;t actually exist within the dictionary. When this is the case, <code>nil<\/code> will be returned. If you think back to the first tutorial in the series, you&#8217;ll remember that variables and constants in Swift cannot be <code>nil<\/code> and must always have a value associated with them. To get around this constraint, Swift provides <em><strong>optionals<\/strong><\/em>, which can either have a value or no value at all (<code>nil<\/code>).<\/p>\n<p>That means that in the example we just looked at, the dictionary&#8217;s subscript is actually returning an optional rather than the value that&#8217;s directly associated with the key. Once you&#8217;ve determined that the optional retrieved from the dictionary isn&#8217;t <code>nil<\/code>, you&#8217;ll need to unwrap it (place an exclamation mark at the end of the optional\u2019s name) to retrieve its value. Here&#8217;s a concrete example:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nlet score = scores[&quot;Bob&quot;]<br \/>\nif score != nil {<br \/>\n&nbsp;&nbsp;println(&quot;Bob&#8217;s score is: \\(score!)&quot;)<br \/>\n} else {<br \/>\n&nbsp;&nbsp;println(&quot;There is no score for Bob&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>As an alternative to using an <code>if<\/code> statement before obtaining an optional\u2019s value, you can also use <em><strong>optional binding<\/strong><\/em>. Here&#8217;s the above example re-written:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nif let score = scores[&quot;Bob&quot;] {<br \/>\n&nbsp;&nbsp;println(&quot;Bob&#8217;s score is: \\(score)&quot;)<br \/>\n} else {<br \/>\n&nbsp;&nbsp;println(&quot;There is no score for Bob&quot;)<br \/>\n}<\/codeswift><\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Create a dictionary that holds the following characters from the Star Wars movies and a force rating for each:<\/p>\n<p><codeswift>Skywalker&nbsp;100<br \/>\nKenobi&nbsp;&nbsp;&nbsp;&nbsp;120<br \/>\nMaul&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;80<br \/>\nVader&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;90<br \/>\nYoda&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1000<br \/>\nWindu&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;110<br \/>\nEmperor&nbsp;&nbsp;&nbsp;200<\/codeswift><\/p>\n<p>Given the following array of names <code>[\"Maul\", \"Vader\", \"Emperor\"]<\/code>, write a program that finds each character&#8217;s rating and prints it to the screen along with their name.<\/div><\/div>\n<p>Subscript syntax can also be used to add new items to a dictionary:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nscores[&quot;Christopher&quot;] = 50000<\/codeswift><\/p>\n<p>The code snippet above adds a new key named <code>Christopher<\/code> and associates a value of <code>50000<\/code> with it.<\/p>\n<p>You can obtain the number of items in a dictionary via its <code>count<\/code> property:<\/p>\n<p><codeswift>var scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nlet numberOfScores = scores.count<\/codeswift><\/p>\n<h3>Iterating Over a Dictionary<\/h3>\n<p>You can use a <code>for-in<\/code> loop to iterate over a dictionary:<\/p>\n<p><codeswift>let scores = [&quot;Amanda&quot;: 10000, &quot;Alan&quot;: 8000, &quot;Freddy&quot;: 1000]<br \/>\nfor (name, score) in scores {<br \/>\n&nbsp;&nbsp;println(&quot;\\(name): \\(score)&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>In the above example, each item in the dictionary is returned as a <code>(key, value)<\/code> tuple. The tuple&#8217;s members are decomposed into constants called <code>name<\/code> and <code>score<\/code>, then printed to the appropriate output as:<\/p>\n<p><codeswift>Amanda: 10000<br \/>\nAlan: 8000<br \/>\nFreddy: 1000<\/codeswift><\/p>\n<p>It&#8217;s possible to retrieve a collection of keys or values from a dictionary via its <code>keys<\/code> and <code>values<\/code> properties. You can then iterate over your collection using a <code>for-in<\/code> loop. Here&#8217;s an example that iterates over the keys from our <code>scores<\/code> array:<\/p>\n<p><codeswift>for name in scores.keys {<br \/>\n&nbsp;&nbsp;println(&quot;Name: \\(name)&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>You can also initialise a new array with either your collection of keys or collection of values. Here&#8217;s an example:<\/p>\n<p><codeswift>let scoresArray = [Int](scores.values)<\/codeswift><\/p>\n<p>Note from the example above that the your array&#8217;s type needs to match the type of the values stored within your dictionary.<\/p>\n<p>It&#8217;s important to remember that items within a dictionary have no specific order. In other words, you can&#8217;t be guaranteed that keys, values, or key-value pairs will be retrieved in any specific order when attempting to iterate over a dictionary.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Create a dictionary that holds the following names and scores:<\/p>\n<p><codeswift>Christopher 10000<br \/>\nAlan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;8000<br \/>\nAmanda&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2500<br \/>\nElizabeth&nbsp;&nbsp;&nbsp;120<br \/>\nFreddy&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;11050<br \/>\nHelen&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;60<br \/>\nCheryl&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;30<\/codeswift><\/p>\n<p>Write a program that iterates over your dictionary and displays the names of those who have scored over 5000 points. Also display each person&#8217;s score alongside their name.<\/div><\/div>\n<h2>While Loops<\/h2>\n<p>Swift provides the familiar <code>while<\/code> and <code>do-while<\/code> loops. Let&#8217;s take a look at the <code>while<\/code> loop.<\/p>\n<h3>While Loop<\/h3>\n<p>The general structure of a <code>while<\/code> loop isn&#8217;t difficult to grasp. Here&#8217;s an example:<\/p>\n<p><codeswift>var index = 0<br \/>\nwhile index < 5 {\n&nbsp;&nbsp;println(&quot;index: \\(index)&quot;)\n&nbsp;&nbsp;index++\n}<\/codeswift><\/p>\n<p>As with the <code>for<\/code> loop (from <a href=\"?p=324\" target=\"_blank\">part one<\/a>), parentheses aren&#8217;t required in Swift. The code above will result in the following output:<\/p>\n<p><codeswift>index: 0<br \/>\nindex: 1<br \/>\nindex: 2<br \/>\nindex: 3<br \/>\nindex: 4<\/codeswift><\/p>\n<p>The <code>while<\/code> loop starts by evaluating its condition. If the condition is <code>true<\/code>, the loop&#8217;s block of statements is repeated until the condition becomes <code>false<\/code>. In the case of our example, the loop continues until the <code>index<\/code> variable no longer has a value less than <code>5<\/code>.<\/p>\n<h3>Do-While Loop<\/h3>\n<p>The <code>do-while<\/code> loop is a variation of the <code>while<\/code> loop. It performs a single pass of the loop&#8217;s block of statements before evaluating the loop&#8217;s condition. Here&#8217;s the previous example rewritten to use a <code>do-while<\/code> loop:<\/p>\n<p><codeswift>var index = 0<br \/>\ndo {<br \/>\n&nbsp;&nbsp;println(&quot;index: \\(index)&quot;)<br \/>\n&nbsp;&nbsp;index++<br \/>\n} while index < 5<\/codeswift><\/p>\n<p>The major difference between both variations is that the <code>do-while<\/code> loop will always execute the statements within its block at least once, whereas a <code>while<\/code> loop&#8217;s block may not execute at all if its condition initially evaluates to <code>false<\/code>.<\/p>\n<p>Don&#8217;t forget about block scope. Variables and constants declared within <code>while<\/code> and <code>do-while<\/code> loops are only valid within the scope of each loop.<\/p>\n<h2>Switch Statement<\/h2>\n<p>Swift&#8217;s <code>switch<\/code> statement is extremely powerful. At a glance it may not look that different from the <code>switch<\/code> statement provided by other languages. Take this simple example as a starting point:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\n&nbsp;&nbsp;break<br \/>\ncase &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\n&nbsp;&nbsp;break<br \/>\ncase &quot;Vader&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\n&nbsp;&nbsp;break<br \/>\ncase &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\n&nbsp;&nbsp;break<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;I don&#8217;t know if \\(name) is a Jedi or Sith&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Running this within your playground will result in <code>Dooku is a Sith<\/code> being displayed in the sidebar. More or less as you&#8217;d expect, right?<\/p>\n<div class=\"zilla-alert white\"> If you&#8217;re an Objective-C developer then you&#8217;ll be delighted to see from the above example that you can switch on strings. While developers of ECMAScript-based languages have always been able to do this, Objective-C&#8217;s roots meant that its <code>switch<\/code> statement had all the hangups of the C programming language. <\/div>\n<p>Our current example uses a <code>break<\/code> statement at the end of each case. However this isn&#8217;t required since <code>switch<\/code> statements in Swift do not automatically fall through to the next case. In other words, we can (and should) rewrite our example with the <code>break<\/code> statements removed:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Vader&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ncase &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;I don&#8217;t know if \\(name) is a Jedi or Sith&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>It should also be noted that <code>switch<\/code> statements in Swift should be exhaustive. What I mean by that is, there should be a matching case statement for every possible value. Where that isn&#8217;t feasible, the <code>default<\/code> keyword should be used to provide a catch-all.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">To verify this, try removing the <code>default<\/code> statement at the end of our current example. You&#8217;ll receive the following error within your playground:<\/p>\n<p><code>Switch must be exhaustive, consider adding a default clause<\/code><\/p>\n<p>Before continuing, add the <code>default<\/code> case back into your code example.<\/div><\/div>\n<p>Looking at our example again, you should notice that the first and second cases produce the same result. The same is also true of the third and fourth cases. You may be tempted to re-factor your <code>switch<\/code> statement like this:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;:<br \/>\ncase &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Vader&quot;:<br \/>\ncase &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;I don&#8217;t know if \\(name) is a Jedi or Sith&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>This code will fail to compile for two reasons. First, as discussed, Swift&#8217;s <code>Switch<\/code> statement does not fall through to the next case by default. Secondly, in Swift, the body of each case must contain at least one executable statement.<\/p>\n<p>To get around this problem, Swift lets you write a comma separated list of matches for a single case. Here&#8217;s how the previous code example should be written:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;, &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Vader&quot;, &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;I don&#8217;t know if \\(name) is a Jedi or Sith&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>We currently print a message if a match is not found for the value of the <code>name<\/code> variable. What if, by design, nothing was to be printed when there was no match? While the use of the <code>break<\/code> statement is discouraged, it actually comes in handy for situations such as this:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;, &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Vader&quot;, &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;break<br \/>\n}<\/codeswift><\/p>\n<h3>Explicit Fallthrough<\/h3>\n<p>As has just been discussed, <code>switch<\/code> statements in Swift do not automatically fall through the bottom of each case and into the next one. Therefore there&#8217;s no need to explicitly place a <code>break<\/code> statement at the end of each case since the execution of your <code>switch<\/code> statement will terminate as soon as the first matching case is completed.<\/p>\n<p>But what if you actually had a need to drop through to the next case? Swift allows you to do that so long as you&#8217;re explicit about it. This prevents the common programming errors you see in other languages where execution dropped through to the <code>switch<\/code> statement&#8217;s next case by accident. The <code>fallthrough<\/code> statement is used for such situations. Here&#8217;s our previous example re-written to use it:<\/p>\n<p><codeswift>var name = &quot;Dooku&quot;<br \/>\nswitch name {<br \/>\ncase &quot;Skywalker&quot;:<br \/>\n&nbsp;&nbsp;fallthrough<br \/>\ncase &quot;Kenobi&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Jedi&quot;)<br \/>\ncase &quot;Vader&quot;<br \/>\n&nbsp;&nbsp;fallthrough<br \/>\ncase &quot;Dooku&quot;:<br \/>\n&nbsp;&nbsp;println(&quot;\\(name) is a Sith&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;break<br \/>\n}<\/codeswift><\/p>\n<p>While the code snippet does technically work, it has been contrived in order to illustrate how the <code>fallthrough<\/code> statement works. If you find yourself writing code like this then you really should consider ditching the <code>fallthrough<\/code> statement and created comma separated lists of matches for each case instead.<\/p>\n<h3>Range Matching<\/h3>\n<p>This is where things get interesting. Swift allows the value in a <code>switch<\/code> statement to be checked against a range. Here&#8217;s our <code>if-else<\/code> code example from <a href=\"?p=324\" target=\"_blank\">part one<\/a>, but this time using a <code>switch<\/code> statement:<\/p>\n<p><codeswift>var energy = 40<br \/>\nswitch energy {<br \/>\ncase 0:<br \/>\n&nbsp;&nbsp;println(&quot;Vader&#8217;s lightsaber cuts through you.&quot;)<br \/>\ncase 1&#46;&#46;&#46;20:<br \/>\n&nbsp;&nbsp;println(&quot;Your powers are weak old man.&quot;)<br \/>\ncase 21&#46;&#46;&#46;40:<br \/>\n&nbsp;&nbsp;println(&quot;You have much to learn.&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;The force is strong with you.&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>The example above would result in <code>You have much to learn.<\/code> being printed to the appropriate output.<\/p>\n<p>We only see the use of the closed range operator <code>(a...b)<\/code> here, but the half-open range operator <code>(a..&lt;b)<\/code> can obviously be used too.<\/p>\n<h3>Tuples<\/h3>\n<p>Tuples can also be matched in a <code>switch<\/code> statement, giving you greater pattern matching capabilities. Here&#8217;s a simple example that recognises types of iOS devices:<\/p>\n<p><codeswift>let currentScreen = (width: 640, height: 1136)<br \/>\nswitch currentScreen {<br \/>\ncase (768, 1024):<br \/>\n&nbsp;&nbsp;println(&quot;A non-Retina iPad&quot;)<br \/>\ncase (1536, 2048):<br \/>\n&nbsp;&nbsp;println(&quot;A Retina iPad&quot;)<br \/>\ncase (320, 480):<br \/>\n&nbsp;&nbsp;println(&quot;A non-Retina iPhone&quot;)<br \/>\ncase (640, 960), (640, 1136), (750, 1334), (1080, 1920):<br \/>\n&nbsp;&nbsp;println(&quot;A Retina iPhone&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;Unknown iDevice&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>This would print <code>A Retina iPhone<\/code> to the appropriate output.<\/p>\n<p>As discussed in <a href=\"?p=324\" target=\"_blank\">part one<\/a>, you can use an underscore to ignore values within a tuple that you aren&#8217;t interested in. In addition, it&#8217;s also possible to use the two range operators when specifying matching tuples:<\/p>\n<p><codeswift>let player = (energy: 10, level: 25)<br \/>\nswitch player {<br \/>\ncase (0, _):<br \/>\n&nbsp;&nbsp;println(&quot;Game Over!&quot;)<br \/>\ncase (1..<10, _):\n&nbsp;&nbsp;println(&quot;Energy Low!&quot;)\ncase (_, 5&#46;&#46;&#46;10):\n&nbsp;&nbsp;println(&quot;Keep up the good progress&quot;)\ncase (_, 11&#46;&#46;&#46;25):\n&nbsp;&nbsp;println(&quot;Awesome! Keep going!&quot;)\ndefault:\n&nbsp;&nbsp;println(&quot;Doing fine&quot;)\n}<\/codeswift><\/p>\n<p>In the above code example, a player&#8217;s status is printed based on their current energy and the game level they have reached. The player&#8217;s health is regarding as being of greater importance, so a message related to their energy will take priority.<\/p>\n<p>This is handled by the first two case statements, with an underscore used to ignore the player&#8217;s current level. The next two are more concerned with the player&#8217;s level progress, with an underscore being employed to ignore the player&#8217;s energy value. Also notice the use of the closed range and half-open range operators throughout the <code>switch<\/code> statement&#8217;s cases.<\/p>\n<p>Running the above code within your playground would result in <code>Awesome! Keep going!<\/code> being displayed in the sidebar.<\/p>\n<p>With these relatively simply examples, we&#8217;re seeing more complex pattern matching capabilities available with Swift&#8217;s <code>switch<\/code> statement compared to languages such as Objective-C or more high-level languages such as JavaScript.<\/p>\n<h3>Value Binding<\/h3>\n<p>The values a <code>switch<\/code> case matches can be bound to temporary constants or variables. These constants and variables can then be used within the case&#8217;s body. Here&#8217;s an example:<\/p>\n<p><codeswift>let player = (energy: 15, level: 100)<br \/>\nswitch player {<br \/>\ncase (0, let level):<br \/>\n&nbsp;&nbsp;println(&quot;Game Over! You reached level \\(level).&quot;)<br \/>\ncase (let energy, 100):<br \/>\n&nbsp;&nbsp;println(&quot;You completed the game with a health of \\(energy).&quot;)<br \/>\ncase let (energy, level):<br \/>\n&nbsp;&nbsp;println(&quot;You are on level \\(level) with a health of \\(energy).&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>This would result in <code>You completed the game with a health of 15.<\/code> being output to your playground&#8217;s sidebar.<\/p>\n<h3>Where<\/h3>\n<p>Finally, a <code>where<\/code> clause can be used in a <code>switch<\/code> statement&#8217;s case to check for additional conditions. Here&#8217;s the previous example with a few more conditions added:<\/p>\n<p><codeswift>let player = (energy: <codeswiftbold>5<\/codeswiftbold>, level: <codeswiftbold>90<\/codeswiftbold>)<br \/>\n<codeswiftbold>let enemyCount = 50<\/codeswiftbold><br \/>\nswitch player {<br \/>\ncase (0, let level):<br \/>\n&nbsp;&nbsp;println(&quot;Game Over! You reached level \\(level).&quot;)<br \/>\ncase (let energy, 100):<br \/>\n&nbsp;&nbsp;println(&quot;You completed the game with a health of \\(energy).&quot;)<br \/>\n<codeswiftbold>case let (energy, level) where enemyCount > 25 &#038;&#038; energy < 10:\n&nbsp;&nbsp;println(&quot;You are being swamped by the enemy and are close to death.&quot;)\ncase let (energy, level) where enemyCount > 25:<br \/>\n&nbsp;&nbsp;println(&quot;You are being swamped by the enemy! Do something!&quot;)<\/codeswiftbold><br \/>\ncase let (energy, level):<br \/>\n&nbsp;&nbsp;println(&quot;You are on level \\(level) with a health of \\(energy).&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>The above example would result in <code>You are being swamped by the enemy and are close to death.<\/code> being sent to the appropriate output.<\/p>\n<p>Notice that our code example introduces a constant named <code>enemyCount<\/code>, which appears in both usages of the <code>where<\/code> clause. The first <code>where<\/code> clause also uses a temporary <code>energy<\/code> constant that is bound to the first tuple value matched by its associated case.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">We have a 2D Cartesian coordinate system that has a square and a rectangle placed on it. The square&#8217;s top-left corner is at (-2, -2) and its bottom-right corner is at (2, 2). The rectangle&#8217;s top-left corner is at (-4, -10) and its bottom-right corner is at (4, 10).<\/p>\n<p>Write a program that takes an (x, y) point and provides feedback as to where that point is. If the point is at the origin then print <code>Is at the origin<\/code> to the appropriate output. If the point is within the square then print <code>Within the square<\/code>. If the point is within the rectangle then print <code>Within the rectangle<\/code>. If the point is lying somewhere along the x-axis then print <code>On the x-axis<\/code>. If the point is lying somewhere on the y-axis then print <code>On the y-axis<\/code>. For any other position, then display <code>Somewhere else<\/code>.<\/p>\n<p>Use a tuple to define the point and take advantage of Swift&#8217;s <code>switch<\/code> statement to determine the point&#8217;s position. Test you code with a few locations such as <code>(0, 0)<\/code>, <code>(1, 1)<\/code>, <code>(3, 6)<\/code>, <code>(0, 20)<\/code>, <code>(20, 0)<\/code>, and <code>(40, 70)<\/code>.<\/div><\/div>\n<p>I hope you can see from these examples just how powerful Swift&#8217;s <code>switch<\/code> statement can be.<\/p>\n<h2>Enums<\/h2>\n<p>If you&#8217;re from a JavaScript or ActionScript background then you may not be familiar with enumerations. If, on the other hand, you&#8217;re familiar with Objective-C or other similar languages then you&#8217;ll be pleasantly surprised by the flexibility of enumerations in Swift.<\/p>\n<p>So what is an enumeration? Put simply, an enumeration is a type that represents a group of related values. For example, you may want to create a type that represents the days of the week, or a type that represents the months in a year. Another example could be a type that represents the four points of a compass.<\/p>\n<p>Let&#8217;s use the days of the week as a concrete example:<\/p>\n<p><codeswift>enum Day {<br \/>\n&nbsp;&nbsp;case Monday<br \/>\n&nbsp;&nbsp;case Tuesday<br \/>\n&nbsp;&nbsp;case Wednesday<br \/>\n&nbsp;&nbsp;case Thursday<br \/>\n&nbsp;&nbsp;case Friday<br \/>\n&nbsp;&nbsp;case Saturday<br \/>\n&nbsp;&nbsp;case Sunday<br \/>\n}<\/codeswift><\/p>\n<p>In the example above we have defined an enumeration type named <code>Day<\/code> that contains the days of the week (<code>Monday<\/code>, <code>Tuesday<\/code>, <code>Wednesday<\/code>, <code>Thursday<\/code>, <code>Friday<\/code>, <code>Saturday<\/code>, and <code>Sunday<\/code>) as its members.<\/p>\n<p>The <code>case<\/code> keyword was used to declare each member of the enumeration. It&#8217;s also possible to comma separate our members on a single line.<\/p>\n<p>Here&#8217;s an alternative way of declaring our enumeration:<\/p>\n<p><codeswift>enum Day {<br \/>\n&nbsp;&nbsp;case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday<br \/>\n}<\/codeswift><\/p>\n<p>Now that our <code>Day<\/code> enumeration type has been created, lets see how to use it:<\/p>\n<p><codeswift>var today = Day.Saturday<\/codeswift><\/p>\n<p>We&#8217;ve just created a variable named <code>today<\/code> that is set to the member <code>Saturday<\/code> from our enumeration. The <code>today<\/code> variable&#8217;s type has been inferred by the fact that it has been initialised with one of the values from <code>Day<\/code>. Once the variable has been initialised, you can use a shorthand syntax to set it to a different value belonging to the enumeration:<\/p>\n<p><codeswift>today = .Sunday<\/codeswift><\/p>\n<p>Of course, the following is also valid, but the shorthand syntax used above is preferred:<\/p>\n<p><codeswift>today = Day.Sunday<\/codeswift> <\/p>\n<h3>Conditional Statements<\/h3>\n<p>As you might expect, an enumeration can be used with <code>if<\/code> statements and <code>switch<\/code> statements. Let&#8217;s start with a simple example that makes use of the <code>if<\/code> statement:<\/p>\n<p><codeswift>var today = Day.Wednesday<br \/>\nif today == .Wednesday {<br \/>\n&nbsp;&nbsp;println(&quot;Swimming lessons today&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>The code snippet above will print <code>Swimming lessons today<\/code> to the appropriate output. Once again, notice the use of the shorthand syntax (<code>.Wednesday<\/code> rather than <code>Day.Wednesay<\/code>) within the <code>if<\/code> statement&#8217;s condition.<\/p>\n<p>Now let&#8217;s take a look at a more sophisticated example that takes advantage of the <code>switch<\/code> statement:<\/p>\n<p><codeswift>var today = Day.Saturday<br \/>\nswitch today {<br \/>\ncase .Monday, .Tuesday, .Wednesday, .Thursday, .Friday:<br \/>\n&nbsp;&nbsp;println(&quot;Work today&quot;)<br \/>\ncase .Saturday, .Sunday:<br \/>\n&nbsp;&nbsp;println(&quot;It&#8217;s the weekend!&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Adding the following to your playground file would result in <code>It's the weekend!<\/code> being displayed within the sidebar.<\/p>\n<p>It&#8217;s also worth noting that the <code>default<\/code> statement wasn&#8217;t used in our <code>switch<\/code> statement. There was no need to because an exhaustive list of all possible enumeration values was provided.<\/p>\n<div data-id='closed' class=\"zilla-toggle\"><span class=\"zilla-toggle-title\">Playground Experiment<\/span><div class=\"zilla-toggle-inner\">Rock-paper-scissors is a game where two players simultaneously form one of three shapes with their hand. The &#8220;rock&#8221; beats scissors, the &#8220;scissors&#8221; beat paper, and &#8220;paper&#8221; beats rock. If both players throw the same shape then the game is tied.<\/p>\n<p>Write a small program that plays out a single game of Rock-paper-scissors.<\/p>\n<p>Declare an enumeration named <code>Shape<\/code> that contains the game&#8217;s three shapes: rock, paper, and scissors.<\/p>\n<p>Declare two constants named <code>player1<\/code> and <code>player2<\/code> to hold each player&#8217;s chosen shape.<\/p>\n<p>Finally, use an <code>if<\/code> statement to handle the logic to determine which player has won. You&#8217;ll also need to handle a tie situation. If player one wins then <code>Player 1 wins<\/code> should be displayed. If player two wins then display <code>Player 2 wins<\/code>. In the event of a tie situation, <code>The game is tied<\/code> should be output.<\/p>\n<p>Test your code by setting different values for your <code>player1<\/code> and <code>player2<\/code> constants.<\/div><\/div>\n<h3>Raw Values<\/h3>\n<p>In programming languages such as Objective-C, each of an enumeration&#8217;s members is assigned an integer value, typically starting from 0 and being incremented for each subsequent member. In Swift, each member is a value in its own right and does not require an integer to be assigned to it. However, you can assign an integer (or any other type) to each member if you so require. These values are known as <em><strong>raw values<\/strong><\/em> and must all be of the same type. <\/p>\n<p>Let&#8217;s take a look at an example where we use an integer to stipulate an order for our days of the week:<\/p>\n<p><codeswift>enum Day<codeswiftbold>: Int<\/codeswiftbold> {<br \/>\n&nbsp;case Monday <codeswiftbold>= 1<\/codeswiftbold>, Tuesday <codeswiftbold>= 2<\/codeswiftbold>, Wednesday <codeswiftbold>= 3<\/codeswiftbold>, Thursday <codeswiftbold>= 4<\/codeswiftbold>, Friday <codeswiftbold>= 5<\/codeswiftbold>,<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Saturday <codeswiftbold>= 6<\/codeswiftbold>, Sunday <codeswiftbold>= 7<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>Notice that we assign a value of <code>1<\/code> to our first member, then increment that value by one for each subsequent member. Doing so isn&#8217;t a requirement. We can assign any arbitrary value to our members. However, if we do wish to apply an incremental sequence of integers to each of our members then we only need to assign a default value to the first member and the remaining values will be inferred:<\/p>\n<p><codeswift>enum Day: Int {<br \/>\n&nbsp;&nbsp;case Monday <codeswiftbold>= 1<\/codeswiftbold>, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday<br \/>\n}<\/codeswift><\/p>\n<p>You can obtain a member&#8217;s raw value with its <code>rawValue<\/code> property:<\/p>\n<p><codeswift>let position = Day.Wednesday.rawValue<br \/>\nprintln(&quot;Today&#8217;s position within the week is: \\(position)&quot;)<\/codeswift><\/p>\n<p>This would result in <code>Today's position within the week is: 3<\/code> being sent to the appropriate output.<\/p>\n<p>It&#8217;s also possible to find an enumeration&#8217;s member based on a raw value. Your enumeration will automatically have an initializer that you can take advantage of. Here&#8217;s an example:<\/p>\n<p><codeswift>let positionToFind = 3<br \/>\nif let day = Day(rawValue: positionToFind) {<br \/>\n&nbsp;&nbsp;if day == .Wednesday {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Swimming lessons today&quot;)<br \/>\n&nbsp;&nbsp;} else {<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;println(&quot;Not up to anything today&quot;)<br \/>\n&nbsp;&nbsp;}<br \/>\n}<\/codeswift><\/p>\n<p>The initializer returns either an enumeration member or <code>nil<\/code> if a member doesn&#8217;t exist for the specified raw value. In other words, it returns an optional enumeration member. Since we are dealing with an optional in our example above, <em><strong>optional binding<\/strong><\/em> is used to ensure that we aren&#8217;t inadvertently working with a variable whose value is <code>nil<\/code>.<\/p>\n<p>The example above will result in <code>Swimming lessons today<\/code> being printed to the appropriate output.<\/p>\n<h3>Associated Values<\/h3>\n<p>We&#8217;ve just seen how the members of an enumeration can be pre-populated with raw values. As an alternative you can also associate a value with an enumeration&#8217;s member. The distinction between the two is that a raw value is fixed to a specific member, whereas an associated value can vary every time you use that member.<\/p>\n<p>As an example, let&#8217;s consider an enumeration that&#8217;s used to represent the status of a construction project. The construction can be either on time, or delayed. Here&#8217;s how that may be represented:<\/p>\n<p><codeswift>enum ConstructionStatus {<br \/>\n&nbsp;&nbsp;case OnTime<br \/>\n&nbsp;&nbsp;case Delayed<br \/>\n}<\/codeswift><\/p>\n<p>With this we can easily create a variable that specifies that a construction project is delayed:<\/p>\n<p><codeswift>var deathStarConstructionStatus = ConstructionStatus.Delayed<\/codeswift><\/p>\n<p>However, we can actually declare a better enumeration that can store information detailing how many months a construction is actually delayed by. Here&#8217;s an improved version of our enumeration:<\/p>\n<p><codeswift>enum ConstructionStatus {<br \/>\n&nbsp;&nbsp;case OnTime<br \/>\n&nbsp;&nbsp;case Delayed<codeswiftbold>(Int)<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>The <code>Delayed<\/code> member now has an integer value associated with it, and that value can be used to store how long (for example, in months) the project has been delayed for. Let&#8217;s take a look at how to use it:<\/p>\n<p><codeswift>var deathStarConstructionStatus = ConstructionStatus.Delayed(6)<\/codeswift><\/p>\n<p>The line above states that construction is six months behind.<\/p>\n<p>If at any point, there are further delays then the variable can be updated:<\/p>\n<p><codeswift>deathStarConstructionStatus = .Delayed(<codeswiftbold>7<\/codeswiftbold>)<\/codeswift><\/p>\n<p>We can use a <code>switch<\/code> statement to check for either of the enumeration&#8217;s members, and also match against any associated values that may belong to them. Here&#8217;s a complete example using our <code>ConstructionStatus<\/code> enumeration type:<\/p>\n<p><codeswift>enum ConstructionStatus {<br \/>\n&nbsp;&nbsp;case OnTime<br \/>\n&nbsp;&nbsp;case Delayed(Int)<br \/>\n}<\/codeswift><\/p>\n<p><codeswift>var deathStarConstructionStatus = ConstructionStatus.Delayed(7)<\/codeswift><\/p>\n<p><codeswift>switch deathStarConstructionStatus {<br \/>\ncase .OnTime:<br \/>\n&nbsp;&nbsp;println(&quot;The Death Star is complete. The Emperor is pleased.&quot;)<br \/>\ncase .Delayed<codeswiftbold>(0&#46;&#46;&#46;3)<\/codeswiftbold>:<br \/>\n&nbsp;&nbsp;println(&quot;Construction is slightly behind schedule.&quot;)<br \/>\ncase .Delayed<codeswiftbold>(4&#46;&#46;&#46;6)<\/codeswiftbold>:<br \/>\n&nbsp;&nbsp;println(&quot;Construction is behind schedule.&quot;)<br \/>\ndefault:<br \/>\n&nbsp;&nbsp;println(&quot;The Emperor is most displeased.&quot;)<br \/>\n}<\/codeswift><\/p>\n<p>Not only are we seeing the flexibility of enumerations within Swift, we&#8217;re also once again seeing just how powerful Swift&#8217;s <code>switch<\/code> statement is. In our code above, we can see the closed range operator being used to specify a case where construction is between 0 and 3 months behind, and another case where construction has been delayed between 4 and 6 months.<\/p>\n<p>It&#8217;s also possible to extract the value associated with an enumeration&#8217;s member. Here&#8217;s the above example re-written to display the actual number of months the project is delayed by if it is already seven months late or more:<\/p>\n<p><codeswift>enum ConstructionStatus {<br \/>\n&nbsp;&nbsp;case OnTime<br \/>\n&nbsp;&nbsp;case Delayed(Int)<br \/>\n}<\/codeswift><\/p>\n<p><codeswift>var deathStarConstructionStatus = ConstructionStatus.Delayed(7)<\/codeswift><\/p>\n<p><codeswift>switch deathStarConstructionStatus {<br \/>\ncase .OnTime:<br \/>\n&nbsp;&nbsp;println(&quot;The Death Star is complete. The Emperor is pleased.&quot;)<br \/>\ncase .Delayed(0&#46;&#46;&#46;3):<br \/>\n&nbsp;&nbsp;println(&quot;Construction is slightly behind schedule.&quot;)<br \/>\ncase .Delayed(4&#46;&#46;&#46;6):<br \/>\n&nbsp;&nbsp;println(&quot;Construction is behind schedule.&quot;)<br \/>\n<codeswiftbold>case .Delayed(let months):<br \/>\n&nbsp;&nbsp;println(&quot;Construction is \\(months) months behind. &quot; +<br \/>\n&nbsp;&nbsp;&nbsp;&nbsp;&quot;The Emperor is most displeased.&quot;)<\/codeswiftbold><br \/>\n}<\/codeswift><\/p>\n<p>I hope you can see the benefit of using Swift&#8217;s enumerations. While we&#8217;ve spent significant time with enumerations, there&#8217;s actually still a lot more to learn. For example, enumerations support many of the features that are traditionally only associated with classes including instance and static methods, but we&#8217;ll leave that for another day.<\/p>\n<h2>Next Time<\/h2>\n<p>Once again we&#8217;ve covered a significant amount of ground. There&#8217;s plenty to digest so please spend as much time as possible experimenting within a playground until you&#8217;re confident you fully understand everything. That goes for many of the language features (optionals, tuples, range operators, etc) from <a href=\"?p=324\" target=\"_blank\">part one<\/a> that were utilised in this second tutorial.<\/p>\n<p>In <a href=\"?p=999\">part three<\/a> we&#8217;ll start by looking at functions before moving on to structures. Structures share many of the same features as classes, and are therefore a good place to start before exploring Swift&#8217;s object-oriented features. <\/p>\n<p>I&#8217;d like to reiterate the message from last time. There really isn&#8217;t anything particularly difficult about the basics of Swift. Coming from other languages, some of Swift&#8217;s concepts may seem unfamiliar, but spend some time working with them and you&#8217;ll quickly be able to master them.<\/p>\n<p>See you in <a href=\"?p=999\">part three<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to the second tutorial in this quick start guide to Swift. We&#8217;ll cover some of the concepts from the first part in more detail while also introducing more language features. What you will learn&#8230; More detail regarding strings How to work with arrays and dictionaries Control flow with while loops and the switch statement [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"footnotes":""},"categories":[13],"tags":[],"class_list":["post-324","post","type-post","status-publish","format-standard","hentry","category-tutorial"],"_links":{"self":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/324","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=324"}],"version-history":[{"count":155,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/324\/revisions"}],"predecessor-version":[{"id":1052,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=\/wp\/v2\/posts\/324\/revisions\/1052"}],"wp:attachment":[{"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=324"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=324"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.yeahbutisitswift.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=324"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}