这是我的字典;
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
for (name) in companies.key {
println(companies.objectForKey("AAPL"))
}
答案 0 :(得分:128)
使用此方法,您可以看到键和值。
var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
for (key, value) in companies {
print("\(key) -> \(value)")
}
或者,如果您只想要值:
for value in companies.values.array {
print("\(value)")
}
在字典上直接访问的一个值:
print(companies["AAPL"])
答案 1 :(得分:21)
来自Apple Docs
您可以使用下标语法从字典中检索特定键的值。因为可以请求不存在值的键,所以字典的下标返回字典值类型的可选值。如果字典包含所请求键的值,则下标返回包含该键的现有值的可选值。否则,下标返回nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
答案 2 :(得分:0)
为了找到下面的价值使用
if let a = companies["AAPL"] {
// a is the value
}
用于遍历字典
for (key, value) in companies {
print(key,"---", value)
}
最后按值搜索键,你首先添加扩展
extension Dictionary where Value: Equatable {
func findKey(forValue val: Value) -> Key? {
return first(where: { $1 == val })?.key
}
}
然后就打电话
companies.findKey(val : "Apple Inc")