Swift - Iterating over a Dictionary

Introduction

There are a couple of ways to iterate through a dictionary.

First, you can use the For-In loop, like this:

Demo

var myTable = [
    "Apple": "iOS",
    "Google" : "Android",
    "Microsoft" : "Windows Phone"
   ]/*from w  w  w .jav a  2s .  c om*/

for platform in myTable {
      print(platform)
}

Result

You can specify the key and value separately:

Demo

var myTable =  [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

for (company, platform) in myTable {
    print("\(company) - \(platform)")
}

Result

You can use the For-In loop to iterate through the keys inside a dictionary using the keys property:

Demo

var myTable =  [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]

for company in myTable.keys {
   print("Company - \(company)")
}

Result

The following example iterates through the values in a dictionary using the values property:

Demo

var myTable =  [
     "Apple": "iOS",
     "Google" : "Android",
     "Microsoft" : "Windows Phone"
]


for platform in myTable.values {
   print("Platform - \(platform)")
}

Result

You can also assign the keys or values of a dictionary directly to an array:

let companies = myTable.keys
let oses = myTable.values

Related Topic