Chapter 05: Dictionary in Swift

What is a Dictionary?
The Dictionary is an unordered List that can be quickly accessed by key

Here is how you can declare an Empty Dictionary

var emptyDictionary = [String : Int]()

Dictionary with Predefined Key Pairs

var apps = ["Productivity" : "Keynote", "Social" : "Facebook", "Music" : "iTunes"]

Accessing the First Key Element of the Dictionary

var optionalApp = apps["Productivity"] // Keynote
if var actualApp = optionalApp {
    print(actualApp) // this will get printed as there is key pair with productivity app inside apps dictionary
} else {
    print("Data Unavailable!")
}

If you want to access some key that doesn’t exist in the Dictionary

var optionalDeveloper = apps["Developer"]
if var actualDeveloper = optionalDeveloper {
    print(actualDeveloper)
} else {
    print("Data Unavailable!") // This will get printed as developer value doesn’t exist in appStore
}

Here is how you can add Key Pair Value to an existing Dictionary

apps["Developer"] = "Xcode"

Here is how you can delete Key Pair Value from the existing Dictionary

apps["Social"] = nil

I hope this blog post will clear your doubt about Dictionary in Swift Programming Language,

Thanks & Regards
Mandar Apte

Published by Mandar Apte

Mandar is a Mumbai-based multi-disciplinary designer with UX/UI, Logo, Symbol, and Brand Identity design expertise. He currently runs his Mudrkashar Linguistic Apple iPhone, iPad, and Mac app business in the heart of Mumbai city.

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.