我的主力博客:半亩方塘
DictionarIEs
1、A dictionary is an unordered collection of pairs,where each pair is comprised ofa keyanda 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 bya colonand 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,"Donna": 6]
In this example,the dictionary has pairs of[String: Int]
. When you print the dictionary,you seethere’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)// > falseprint(namesAndscores.count)// > 4print(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 andreturns the old value. If the key doesn’t exist,this method willadd a new pairand returnnil
.
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
Assigningnil
as a key’s associated value removes the pair from the dictionary.
5、Thefor-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 thevalues
property on the dictionary.
6、You Could usereduce(_:combine:)
to replace the prevIoUs code snippet with a single line of code:
let namesstring = namesAndscores.reduce("",combine: {
+ "\(.0)," })print(namesstring)
In a reduce statement,.0
refers to the partially-combined result,andkey
refers to the current element. Since the elements in a dictionary are tuples,you need to usefilter(_:)
to get the
print(namesAndscores.filter({ to access the.1
.1 < 5 }))// > [("Brian",2),("Anna",2)]
of the pair. Let’s see how you Could usevalue
to find all the players with a score of less than 5:
Here you use
总结以上是内存溢出为你收集整理的Swift 笔记(十)全部内容,希望文章能够帮你解决Swift 笔记(十)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)