相比于Array需要按照顺序获取内容,Dictionary有一个专门的key来获取相对应的数值。
1. Syntax
full : Dictionary<key, value>
shorthand: [key: value]
2. Creating
var namesOfIntegers: [Int: String] = [ : ] //创建一个空的dictionary,类型为[Int: String]
var namesOfIntegers: [Int: String] = [1:"lsfj",2:"fjaiejf"]
var namesOfIntegers = [1:"lsfj",2:"fjaiejf"] //这条和上面一条等同
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
3. Accessing and Modifying
Dictionary也有很多属性和方法,很类似于Array,具体的可以阅读Xcode->help->developer Documentation中的相关内容。下面列出了常见的几个
先创建一个dictionary,以下代码都用的这个var。
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
print("The airports dictionary contains \(airports.count) items.")
isEmpty
if airports.isEmpty {
print("The airports dictionary is empty.")
}
add a new item
airports["LHR"] = "London"
change the value by subscript syntax
airports["LHR"] = "London Heathrow"
change the value by updataValue method
if let oldValue = airports.updateValue("Dubling Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue)")
} else{
print("There was no value for key DUB")
}
retrieve a value by subscript syntax
if let aiportName = airports["DUB"] {
print("The name of the airport is \(aiportName)")
} else {
print("That airport isn't in the airport dictionary")
}
remove a key-value pair by subscript syntax
airports["APL"] = "Apple International"
airports["APL"] = nil
remove a key-value pair by removeValue
if let removeValue = airports.removeValue(forKey: "DUB") {
print("The removed aireport's name is \(removeValue) .")
} else {
print("The airports dictionary doesn't contain a value for DUB.")
}
get a dictionary's keys or values
let airportCodes = [String](airports.keys)
let airportNames = [String](airports.values)
4. Iterating Over a Dictionary
keys 和 values 都需要的时候
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
只需要keys时
for airportCode in airports.keys {
print("Airport Code: \(airportCode)")
}
只需要values时
for airportName in airports.values {
print("Airport Name: \(airportName)")
}
5. Default Value
获取dictionary中的值得时候有时候会返回nil,当你不想要这样的返回值而是想要给没有的key一个默认值时可以这样写
let airportName = airports["DDR", default: "nothing"]