Menu
Coddy logo textTech

Declaring Dictionaries

Part of the Logic & Flow section of Coddy's Swift journey — lesson 12 of 56.

A dictionary is an unordered collection of key/value pairs. Both the key type and the value type are fixed when you create it.

var prices: [String: Int] = [
    "apple": 1,
    "bread": 3,
    "milk":  4
]
print(prices.count)            // 3
print(prices.isEmpty)          // false

The type annotation [String: Int] reads as "keys are String, values are Int". Swift can usually infer it from the literal, but writing it out makes empty initializers unambiguous:

var counts: [String: Int] = [:]
// vs. an empty array, which would need a type too

Reading a key that exists returns the value. Reading a key that doesn't returns nil, the next lesson covers that part.

challenge icon

Challenge

Easy

Read three lines of input: a name, a country, and an integer age. Build a single dictionary called person with String keys and the values you read in (the age stays an Int, you'll need a heterogeneous value type, see the hint).

Print three lines:

  1. The number of entries in the dictionary
  2. name=<value> using subscript access
  3. country=<value> using subscript access

Use the printable form: when you read the dictionary value as an Any, force-unwrap it before printing.

For input Alice / UK / 30, the output is:

3
name=Alice
country=UK

Cheat sheet

A dictionary stores key/value pairs with fixed key and value types:

var prices: [String: Int] = [
    "apple": 1,
    "bread": 3,
    "milk":  4
]
print(prices.count)   // 3
print(prices.isEmpty) // false

Create an empty dictionary with explicit type annotation:

var counts: [String: Int] = [:]

Use [String: Any] for heterogeneous value types (mixed types):

var person: [String: Any] = [
    "name": "Alice",
    "age": 30
]

Try it yourself

let name = readLine()!
let country = readLine()!
let age = Int(readLine()!)!

// TODO: build a [String: Any] called person, print count, name, country
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow