Using Dictionaries

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

When you first start out, you’ll be using lots of arrays, but the dictionary is another collection that is also quite useful. Whereas an array retrieve values based on an index, dictionaries work using key value pairs.

You can think of a dictionary collection much like a regular dictionary. To find the meaning of word, you look up the definition based on the word itself. In the physical dictionary, words are listed in alphabetical order. With a Swift dictionary, you don’t to word about how it is organized. You simply provide the key and the dictionary returns a value.

Swift dictionaries also allow you to define the types of the keys and the values. For instance, you may create a baseball dictionary. This dictionary stores player names by their number. For example, if you had a Dodgers dictionary, you’d pass in the number 42 as the key, and receive Jackie Robinson as the value.

Creating a Dictionary

Creating a dictionary looks a little strange, but like all things with code, you’ll get used to it in time. Here’s a dictionary that uses Strings for both the key and the value.

var animalNames: [String: String] = [:]
var animalNames: 
[String: String] 
= [:]
var animalNames = [ "🐕": "Dog"]

Reading Values

Once you have a dictionary created in code, it’s just a matter of getting in setting values. To simply get the value, you pass in the key to the dictionary.

print(animalNames["🐕"]) // prints Dog
print(animalNames["🐍"]) // prints nil
var name: String? = animalNames["🐍"]
if let name {
  print(name)
}

Setting Values

You can also easily set values for existing dictionaries. As with all variables, you must be aware of the type names. In the case of the snake, you can simply set the key and the values. For example:

animalNames["🐍"] = "Snake"
See forum comments
Download course materials from Github
Previous: Demo: Loops & Arrays Next: Conclusion