Swift Dictionary Example

1. Introduction

Dictionaries in Swift are collections of key-value pairs where each key is unique. They are similar to arrays, but rather than storing values in an ordered list, dictionaries store them in a way that lets you access any value based on its corresponding key. This makes fetching values from a dictionary extremely efficient.

2. Source Code Example

// Creating a dictionary with String keys and Int values
var scores: [String: Int] = ["Alice": 5, "Bob": 3, "Charlie": 8]

// Accessing a value using a key
let aliceScore = scores["Alice"]

// Adding a new key-value pair
scores["David"] = 6

// Modifying a value using its key
scores["Bob"] = 7

// Removing a key-value pair
scores["Charlie"] = nil

// Iterating over a dictionary's keys and values
for (name, score) in scores {
    print("\(name): \(score)")
}

// Using the `keys` and `values` properties to iterate
for name in scores.keys {
    print(name)
}

for score in scores.values {
    print(score)
}

// Checking if dictionary contains a specific key
let hasCharlie = scores.keys.contains("Charlie")

print("Contains key 'Charlie'? \(hasCharlie)")

Output:

Alice: 5
Bob: 7
David: 6
Alice
Bob
David
5
7
6
Contains key 'Charlie'? false

3. Step By Step Explanation

1. A dictionary named scores is created with String keys and Int values.

2. You can access a value in the dictionary directly using its key.

3. Adding a new key-value pair is as simple as assigning a value to a new key.

4. Modifying a value is similar to adding; you just assign a new value to an existing key.

5. Setting a value for a key to nil will remove that key-value pair from the dictionary.

6. You can iterate over all key-value pairs in a dictionary using a for-in loop.

7. The keys and values properties of a dictionary allow you to iterate over its keys or values, respectively.

8. The keys.contains(_:) method checks if the dictionary contains a specific key.


Comments