Pete On Software

RSS Feed

Swift – Collections and Iterations

Apple's Swift LanguageLast 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 a look at how Swift does iteration over collections.

To declare an array, you can just use this simple syntax. Note that unlike Objective-C, you don’t have to nil terminate the array. Arrays are also zero-based, so given the array below, the value of favoritePodcasts[0] is “Hanselminutes”.

The dictionary syntax is very similar to the array syntax and looks a lot like JavaScript JSON syntax.

To access one of the entries, you just call it with the key, like JSON. In this case podcastHosts[“iPhreaks”] would be “Charles Max Wood et al”.

If you want to just declare an array or dictionary, you just use this simple syntax.

UPDATE 7/16/2014: In Xcode 6 Beta 3, the Swift syntax for arrays was changed from String[]() to [String]()

Now, let’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.

This gives us the following output in the XCode Playground when I include it after the code that we’ve already written:
Swift Iterate an Array

Let’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’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.

That will give us this result to the console:
Swift Iterate Array and Access Dictionary

What if I wanted to iterate over the dictionary? Again, we are going to find some very familiar syntax. I’m going to make a new dictionary below and then iterate over it, writing out the values. You’ll notice that unlike some languages, you get both variables declared in the for syntax, and you don’t have to iterate keys and then access the values from the dictionaries.

That gives us the following output:
Swift Dictionary Iteration

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.

That’s it for this time. This post was starting to get a little long, so I’m going to save control flow for next time to try to keep this as focused and non-rambling as possible.

One Comment

Swift – Control Structures  on June 25th, 2014

[…] the previous post in this Swift series, we looked at collections and iterating over those collections. In this post, […]

Leave a Comment