Swift for-in loop

Written on July 16, 2016

I’ve been trying to pick up Swift recently. One of the things that I thought was interesting about Swift is how dictionaries are accessed with a for-in loop.

// Swift for-in loop
var pizzaPrices = [
  "small": 4.99,
  "medium": 5.99,
  "large": 6.99

for (size, price) in pizzaPrices{
  print("\(size): $\(price)")

The interesting thing about the for-in loop is how the key-value pair is accessed. As you can see a pair of names (size, price) are given to use for each key-value pair.

Contrast this to how a key-value pair is accessed in a dictionary in JavaScript:

// JavaScript for-in loop
var pizzaPrices = {
  'small': 4.99,
  'medium': 5.99,
  'large': 6.99

for(pizza in pizzaPrices) {
  console.log(pizza + ": $" + pizzaPrices[pizza])

In JavaScript, you’ll see that a name pizza is given to refer to the key but a name isn’t given for the value of the key. To access the value you pass the key into the dictionary pizzaPrices which then returns the value for the passed key.

The Swift syntax is going to take a little time to get used to but I’m liking the explicit names given to reference the key-value pair of dictionaries.

Stay in touch

Thanks for reading this article. I'd love to stay in touch and share articles like this one in your inbox. Sign up for my newsletter.