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