0
0
Swiftprogramming~3 mins

Why Dictionary creation and access in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find any piece of information instantly, no matter how big your list grows?

The Scenario

Imagine you have a list of friends and their phone numbers written on paper. Every time you want to find a number, you have to scan the whole list from top to bottom.

The Problem

This manual search is slow and frustrating. If the list is long, you might make mistakes or miss the number you want. It's hard to keep the list organized and update it quickly.

The Solution

Using a dictionary in Swift lets you store each friend's name as a key and their phone number as a value. You can find any number instantly by using the friend's name, without searching through the whole list.

Before vs After
Before
let friends = [("Alice", "123"), ("Bob", "456")]
var number = ""
for friend in friends {
  if friend.0 == "Bob" {
    number = friend.1
  }
}
After
let friends = ["Alice": "123", "Bob": "456"]
let number = friends["Bob"]
What It Enables

It makes finding, adding, or changing information fast and easy, just like looking up a word in a dictionary.

Real Life Example

Apps use dictionaries to quickly find user settings, like language or theme, without slowing down the app.

Key Takeaways

Dictionaries store data as key-value pairs for quick access.

They save time by avoiding long searches.

They make your code cleaner and easier to update.