Lesson 8 of 15

Dictionaries

Dictionaries

Dictionaries store key-value pairs:

var scores = ["Alice": 95, "Bob": 82, "Charlie": 78]

Accessing Values

Dictionary lookups return an optional because the key might not exist:

let aliceScore = scores["Alice"] ?? 0   // 95
let daveScore = scores["Dave"] ?? 0     // 0 (default)

Adding and Updating

scores["Dave"] = 91     // add new entry
scores["Alice"] = 100   // update existing

Iterating

for (name, score) in scores {
    print("\(name): \(score)")
}

Your Task

Write a function countFrequency that takes an array of strings and a target string, and returns how many times the target appears in the array.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.