我的主力博客:半畝方塘
Dictionaries
1、A dictionary is an unordered collection of pairs, where each pair is comprised of a keyand a value. The same key can’t appear twice in a dictionary, but different keys may point to the same value. All keys have to be of the same type, and all values have to be of the same type.
2、When you create a dictionary, you can explicitly declare the type of the keys and the type of the values:
let pairs: Dictionary<String, Int>
Swift can also infer the type of a dictionary from the type of the initializer:
let inferredPairs = Dictionary<String, Int>()
Or written with the preferred shorthand:
let alsoInferredPairs = [String: Int]()
Within the square brackets, the type of the keys is followed by a colon and the type of the values. This is the most common way to declare a dictionary.
If you want to declare a dictionary with initial values, you can use a dictionary literal. This is a list of key-value pairs separated by commas, enclosed in square brackets:
let namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
print(namesAndScores)
// > ["Brian": 2, "Anna": 2, "Craig": 8, "Donna": 6]
In this example, the dictionary has pairs of [String: Int]
. When
you print the dictionary, you see there’s no particular order to the pairs.
An empty dictionary literal looks like this: [:].
You can use that
to empty an existing dictionary like so:
var emptyDictionary: [Int: Int]
emptyDictionary = [:]
print(namesAndScores["Anna"])
// > Optional(2)
Notice that the return type is an optional. The dictionary will check if there’s a pair with the key “Anna”, and if there is, return its value. If the dictionary doesn’t find the key, it will return
nil:
print(namesAndScores["Greg"])
// > nil
Properties and methods:
print(namesAndScores.isEmpty)
// > false
print(namesAndScores.count)
// > 4
print(Array(namesAndScores.keys))
// > ["Brian", "Anna", "Craig", "Donna"]
print(Array(namesAndScores.values))
// > [2, 2, 8, 6]
4、Take a look at Bob’s info:
var bobData = ["name": "Bob", "profession": "Card Player", "country": "USA"]
Let’s say you got more information about Bob and you wanted to add it to the dictionary. This is how you’d do it:
bobData.updateValue("CA", forKey: "state")
There’s even a shorter way, using subscripting:
bobData["city"] = "San Francisco"
You want to change Bob’s name from Bob to Bobby:
bobData.updateValue("Bobby", forKey: "name"]
// > Bob
Why does it return the string “Bob”? updateValue(_:forKey:)
replaces
the value of the given key with the new value and returns the old value. If the key doesn’t exist, this method will add
a new pair and return nil
.
As with adding, you can change his profession with less code by using subscripting:
bobData["profession"] = "Mailman"
Like the first method, the code updates the value for this key or, if the key doesn’t exist, creates a new pair.
You want to remove all information about his whereabouts:
bobData.removeValueForKey("state")
As you might expect, there’s a shorter way to do this using subscripting:
bobData["city"] = nil
Assigning nil
as
a key’s associated value removes the pair from the dictionary.
5、The for-in
loop also works when you want to iterate over a dictionary.
But since the items in a dictionary are pairs, you need to use tuple:
for (key, value) in namesAndScores {
print("\(key) - \(value)")
}
// > Brian - 2
// > Anna - 2
// > Craig - 8
// > Donna - 6
It’s also possible to iterate over just the keys:
for key in namesAndScores.keys {
print("\(key),", terminator: "") // no newline
}
print("") // print one final newline
// > Brian, Anna, Craig, Donna,
You can iterate over just the values in the same manner with the values
property
on the dictionary.
6、You could use reduce(_:combine:)
to replace the previous code
snippet with a single line of code:
let namesString = namesAndScores.reduce("", combine: { $0 + "\($1.0)," })
print(namesString)
In a reduce statement, $0
refers to the partially-combined result,
and $1
refers to the current element. Since the elements in a
dictionary are tuples, you need to use $1.0
to get the key
of
the pair.
Let’s see how you could use filter(_:)
to find all the players
with a score of less than 5:
print(namesAndScores.filter({ $0.1 < 5 }))
// > [("Brian", 2), ("Anna", 2)]
Here you use $0.1
to
access the value
of
the pair.