- Mastering macOS Programming
- Stuart Grimshaw
- 403字
- 2021-07-02 22:54:15
Dictionaries
Dictionary objects look like this:
let myDict = ["One":"Eins", "Two":"Zwei", "Three":"Drei"]
They are how Swift stores key-value pairs. A value is set and retrieved by using its key instead of an index, as one would with an array. Each key can occur only once in any particular Dictionary.
Dictionary keys must be objects that conform to the Hashable protocol; these include String and Int objects.
Like the Array, Dictionary objects also come equipped with a pretty standard set of methods:
let count2 = myDict.count
let uno = myDict["One"] // "Eins"
If the Dictionary does not contain a key-value pair with the required key, it returns nil:
let quattro = myDict["Four"]
So, quattro will be nil.
We declare a mutable Dictionary with var:
var varDict = ["One": "Eins", "Two": "Zwei"]
A key-value pair is added to and removed from a mutable Dictionary as follows:
varDict["Three"] = "Drei"
varDict.removeValue(forKey: "One")
No prizes for guessing that values for existing keys are changed as follows:
varDict["One"] = "Een"
We can declare a Dictionary object without initializing it, as follows:
var emptyDict1: [String: String]
var emptyDict2: Dictionary<String, String>
These two methods are equivalent (the parallels with Array declarations are obvious). We declare and initialize an empty Dictionary with one of the following methods:
var emptyDict3 = [String: String]()
var emptyDict4: [String: String] = [:]
var emptyDict5: Dictionary<String, String> = [:]
Once the type of Dictionary is clear:
var myDict = ["One": "Eins", "Two": "Zwei", "Three": "Drei"]
(here, myDict is initialized as a Dictionary of type <String: String>), we can set it to the empty array with just the empty brackets:
myDict = [:]
Don't forget the colon, though; it's not an Array.
If we declare a Dictionary object with let, we cannot change its values:
let constDict = ["One": "Eins", "Two": "Zwei"]
constDict["One"] = "Un"
The second line will produce a compiler error.
You may find that it is frequently helpful to use a typealias to name a particular Dictionary type:
typealias memberRank = [String: Int]