Dictionaries
A dictionary is a collection of objects of the same type that is identified using a key. Consider the following example:
var platforms = [
"Apple": "iOS",
"Google" : "Android",
"Microsoft" : "Windows Phone"
]
Here, platforms is a dictionary containing three items. Each item is a key/value pair. For example, "Apple" is the key that contains the value "iOS".
Unlike arrays, the ordering of items in a dictionary is not important. This is because an item is identified by the key and not the index. The above could also be written like this:
var platforms = [
"Microsoft" : "Windows Phone",
"Google" : "Android",
"Apple": "iOS"
]
The key of an item in a dictionary is not limited to String - it can be any of the hashable type (i.e. it must be uniquely representable). Th following example shows a dictionary using integer as its key:
var ranking = [
1: "Gold",
2: "Silver",
3: "Bronze"
]
To access an item in a dictionary, specify its key:
let platform = platforms["Apple"] // "iOS"
To know the number of items within a dictionary, use the count property:
var platformsCount = platforms.count // 3
To replace the value of an item, specify its key and assign a value to it:
platforms["Microsoft"] = "WinPhone"
To remove an item from a dictionary, you can simply set it to nil:
platforms["Microsoft"] = nil;
platformsCount = platforms.count // 2
The number of items inside the dictionary would now be reduced by one.
To insert a new item into the dictionary, you specify a new key and assign it a value, like this:
platforms["Samsung"] = "Tizen"
The value of a key can itself be another array as the following example shows:
var products = [
platforms["Apple"]: ["iPhone", "iPad", "iPod touch"],
platforms["Google"]: ["Nexus 3", "Nexus 4", "Nexus 5"],
platforms["Microsoft"] : ["Lumia 920", "Lumia 1320","Lumia 1520"]
]
To access a particular product in the above example, you would first specify the key of the item you want to retrieve, followed by the index of the array, like this:
var product1 = products["Apple"][0]
Mutabilities of Dictionaries
When creating a dictionary, its mutability (its ability to change its size after it has been created) is dependent of you using either the let or var keyword. If you used the let keyword, the dictionary is immutable (its size cannot be changed after it has been created) as you are creating a constant. If you used the var keyword, the dictionary is mutable (its size can be changed after its creation) as you are now creating a variable.
See Also
Arrays
No comments:
Post a Comment