关闭

Swift教程之NSDictionary

标签: dictionaryswift字典基础语法
318人阅读 评论(0) 收藏 举报
分类:
//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)

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:274163次
    • 积分:7265
    • 等级:
    • 排名:第3058名
    • 原创:471篇
    • 转载:68篇
    • 译文:2篇
    • 评论:27条
    最新评论