{"id":689,"date":"2014-06-24T19:01:35","date_gmt":"2014-06-24T23:01:35","guid":{"rendered":"http:\/\/www.peteonsoftware.com\/?p=689"},"modified":"2024-03-02T16:21:57","modified_gmt":"2024-03-02T21:21:57","slug":"swift-collections-and-iterations","status":"publish","type":"post","link":"https:\/\/www.peteonsoftware.com\/index.php\/2014\/06\/24\/swift-collections-and-iterations\/","title":{"rendered":"Swift &#8211; Collections and Iterations"},"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;\"><a href=\"https:\/\/www.peteonsoftware.com\/index.php\/2014\/06\/16\/intro-to-the-swift-programming-language\/\">Last time<\/a>, we had a small intro to Swift and saw how to declare simple variables and do some string work.  This time, we are going to look at some more complex types and take a look at how Swift does iteration over collections.<\/p>\n<p>To declare an array, you can just use this simple syntax.  Note that unlike Objective-C, you don&#8217;t have to nil terminate the array.  Arrays are also zero-based, so given the array below, the value of favoritePodcasts[0] is &#8220;Hanselminutes&#8221;. <\/p>\n<pre>\r\nvar favoritePodcasts = [\"Hanselminutes\", \".Net Rocks!\", \r\n     \"iPhreaks\", \"Pete on Software Podcast\"]\r\n<\/pre>\n<p>The dictionary syntax is very similar to the array syntax and looks a lot like JavaScript JSON syntax.  <\/p>\n<pre>\r\nvar podcastHosts = [\r\n    \"Hanselminutes\" : \"Scott Hanselman\",\r\n    \".Net Rocks!\" : \"Carl Franklin and Richard Campbell\",\r\n    \"iPhreaks\" : \"Charles Max Wood et al\",\r\n    \"Pete on Software Podcast\" : \"Pete Shearer\"\r\n]\r\n<\/pre>\n<p>To access one of the entries, you just call it with the key, like JSON.  In this case podcastHosts[&#8220;iPhreaks&#8221;] would be &#8220;Charles Max Wood et al&#8221;.<\/p>\n<p>If you want to just declare an array or dictionary, you just use this simple syntax.  <\/p>\n<pre>\r\nvar emptyArray = [String]()\r\nvar emptyDictionary = Dictionary&lt;Int, String&gt;()\r\n<\/pre>\n<p><em>UPDATE 7\/16\/2014: In Xcode 6 Beta 3, the Swift syntax for arrays was changed from String[]() to [String]()<\/em><\/p>\n<p>Now, let&#8217;s look at how we can iterate over these collections.  This should be very comfortable syntax if you are familiar with JavaScript, minus the parentheses.<\/p>\n<pre>\r\nfor podcast in favoritePodcasts {\r\n    println(podcast)\r\n}\r\n<\/pre>\n<p>This gives us the following output in the XCode Playground when I include it after the code that we&#8217;ve already written:<br \/>\n<img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/SwiftIterateArray.png\" alt=\"Swift Iterate an Array\" title=\"Swift Iterate an Array\" \/><\/p>\n<p>Let&#8217;s take this up another notch and for each podcast, pull out its hosts from the dictionary and write those hosts to the console.  We&#8217;ll use the iteration flow we just covered, the key-value dictionary retrieval syntax, and the string interpolation that we looked at last time to accomplish this.<\/p>\n<pre>\r\nfor podcast in favoritePodcasts {\r\n    var host = podcastHosts[podcast]\r\n    println(\"\\(podcast) is hosted by \\(host)\")\r\n}\r\n<\/pre>\n<p>That will give us this result to the console:<br \/>\n<img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/SwiftArrayAndDictionary.png\" alt=\"Swift Iterate Array and Access Dictionary\" title=\"Swift Iterate Array and Access Dictionary\" \/><\/p>\n<p>What if I wanted to iterate over the dictionary?  Again, we are going to find some very familiar syntax.  I&#8217;m going to make a new dictionary below and then iterate over it, writing out the values.  You&#8217;ll notice that unlike some languages, you get both variables declared in the for syntax, and you don&#8217;t have to iterate keys and then access the values from the dictionaries.<\/p>\n<pre>\r\nvar citiesAndBaseballTeams = [\r\n    \"Cincinnati\" : \"Reds\",\r\n    \"Pittsburgh\" : \"Pirates\",\r\n    \"Cleveland\" : \"Indians\",\r\n    \"Oakland\" : \"Athletics\"\r\n]\r\n\r\nfor (city, team) in citiesAndBaseballTeams {\r\n    println(\"The \\(team) play in \\(city)\")\r\n}\r\n<\/pre>\n<p>That gives us the following output:<br \/>\n<img decoding=\"async\" src=\"https:\/\/www.peteonsoftware.com\/images\/201406\/SwiftDictionaryIteration.png\" alt=\"Swift Dictionary Iteration\" title=\"Swift Dictionary Iteration\" \/><\/p>\n<p>It is interesting to note that I did not change anything.  It did print out of order with how I added those items.  The dictionaries are definitely not expected to keep any kind of order for you when you iterate over them.<\/p>\n<p>That&#8217;s it for this time.  This post was starting to get a little long, so I&#8217;m going to save control flow for next time to try to keep this as focused and non-rambling as possible.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Last time, we had a small intro to Swift and saw how to declare simple variables and do some string work. This time, we are going to look at some more complex types and take &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-689","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\/689","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=689"}],"version-history":[{"count":0,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/posts\/689\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/media?parent=689"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/categories?post=689"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.peteonsoftware.com\/index.php\/wp-json\/wp\/v2\/tags?post=689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}