前端之家收集整理的这篇文章主要介绍了
Swift教程之NSDictionary,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//MARK:----------字典--------------
/* 字典(key : value)*/
//如果类型信息已知,使用[:]声明空字典。
let emptyDictionary1 = [:]
let emptyDictionary2 = Dictionary<String,Float>()
let emptyDictionary3 = [String: Float]()
print(emptyDictionary2.count)
//var airports: Dictionary<String,String> = ["TYO": "Tokyo","DUB": "Dublin"]
var airportsDic = ["TYO": "Tokyo","DUB": "Dublin"]
print(airportsDic["TYO"])
//---------添加----------
airportsDic["LHR"] = "London"
print(airportsDic)
//-------修改------
airportsDic["LHR"] = "London Heathrow" // the value for "LHR" has been changed to "London Heathrow
print(airportsDic)
//等价于
//airports.updateValue("Dublin International",forKey: "DUB")
//print(airports)
//------------删除-----------
airportsDic["LHR"] = nil
print(airportsDic)
//等价于
//airportsDic("DUB")
//print(airportsDic)
//---------查询----------
print("字典元素个数为" + String(airportsDic.count))
print("字典包含 \(airportsDic.count) 个元素.")
print(airportsDic.startIndex)
print(airportsDic.endIndex)
//-------------遍历字典-----------
for (key,Value) in airportsDic
{
print("\(key): \(Value)")
}
for key in airportsDic.keys
{
print("Airport code: \(key)")
}
for Value in airportsDic.values
{
print("Airport name: \(Value)")
}
let airportKeys = Array(airportsDic.keys) // airportCodes is ["TYO","LHR"]
let airportValues = Array(airportsDic.values) // airportNames is ["Tokyo","London Heathrow"]
print(airportKeys)
print(airportValues)