逆钟夕的忘忧阁

有朋自远方来,不亦乐乎?

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)

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pengyuan_D/article/details/46816103
个人分类: Swift教程
上一篇Swift教程之NSArray
下一篇Swift教程之元组类型
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭