Chapter 05: Let’s Learn Swift Programming Language – Dictionary in Swift

What is Dictionary?

 
Dictionary is unordered List which can be quickly access by key

 
Here is how you can declare Empty Dictionary

var emptyDictionary = [String : Int]()

 
Dictionary with Predefined Key Pairs

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

 
Accessing First Key Element of 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 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 existing Dictionary

apps["Developer"] = "Xcode"

 
Here is how you can deleting Key Pair Value from existing Dictionary

apps["Social"] = nil

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

 
Thanks & Regards
Mandar Apte

Mandar Apte

This website contains a design articles blog by Mandar Apte. He writes and shares his iOS development, graphic, web, & animation film design experience through articles. Mandar is Mumbai based multi-disciplinary designer with expertise in UI, UX, Logo, Symbol, and Brand Identity design. He is an alumnus of Sir J. J. Institute of Applied Art, Mumbai. He currently runs his studio in the heart of the city of Mumbai.

Leave a Reply

Your email address will not be published. Required fields are marked *