Start learning free

LESSON 101 OF 349 · DICTIONARIES

Dictionaries in Swift in Swift

Lesson

In Swift, a Dictionary stores key-value pairs where each key maps to a value.

var scores: [String: Int] = [:]
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72

Use [String: Int] to declare a dictionary where keys are strings and values are integers. Use dict[key] = value to add entries:

var ages: [String: Int] = [:]
ages["Alice"] = 25
ages["Bob"] = 30
print(ages["Alice"]!)  // 25
print(ages.count)      // 2

Assignment
Follow the Coding Tutorial and create a Dictionary named scores with three student scores!


Hint
Declare var scores: [String: Int] = [:] then use scores[key] = value to add entries.

STEP 1 OF 2
    Ctrl + Enter to check

    Dictionaries in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free