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) // falseThe 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 tooReading a key that exists returns the value. Reading a key that doesn't returns nil, the next lesson covers that part.
Challenge
EasyRead 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:
- The number of entries in the dictionary
name=<value>using subscript accesscountry=<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=UKCheat 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) // falseCreate 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check3Dictionaries
Declaring DictionariesOptional LookupUpdating DictionariesIterating DictionariesGrouping ValuesRecap - Inventory