Dictionary in swift are used to key value pairs of some data type. The syntax for dictionary in swift is as shown below.

var (or let for constant) myFirstDictionary = [Key:value.. Key:Value]

Some example dictionaries are shown below.

var myFirstDictionary = [:]
println("myFirstDictionary:\(myFirstDictionary)")
var mySecondDictionary = ["Key1":"Value1","Key2":"Value2"]
println("mySecondDictionary:\(mySecondDictionary)")
var myThirdDictionary:Dictionary = ["Key1":"Value1","Key2":"Value2"]
println("myThirdDictionary:\(myThirdDictionary)")
var myOptionalFourthDictionary:Array?
println("myOptionalFourthDictionary:\(myOptionalFourthDictionary)")

When you run the above program, we will get the following output.

myFirstDictionary:{
}
mySecondDictionary:[Key2: Value2, Key1: Value1]
myThirdDictionary:[Key2: Value2, Key1: Value1]
myOptionalFourthDictionary:nil

Adding Values to an Dictionary

In array, adding values is made easy with the use simple hashing structure. An example is shown below

var myDictionary:Dictionary = [:]
myDictionary["Key1"] = "New Value 1"
println("myDictionary:\(myDictionary)")

When you run the above program, we will get the following output.

myDictionary:[Key1: New Value 1]