• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

【Swift学习】Swift编程之旅---集合类型之字典(八)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

  字典是一种存储相同类型多重数据的存储器。每个值(value)都关联独特的键(key),键作为字典中的这个值数据的标识符。和数组中的数据项不同,字典中的数据项并没有具体顺序。

  字典写作Dictionary<Key, Value>。也可以写作[Key: Value]

 

  创建空字典

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

 

  类型推断写作[:]

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

 

 

  创建字典字面量

[key 1: value 1, key 2: value 2, key 3: value 3]

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

 

  类型推断写作

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

 

 

  访问和修改

  count返回字典的键值对数

  isEmpty判断字典是否为空

  

airports["LHR"] = "London Heathrow

 

 

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin.

 

 

  removeValueForKey(_:)删除键值对  

if let removedValue = airports.removeValueForKey("DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}
// Prints "The removed airport's name is Dublin Airport.

 

 

 遍历

for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

 

 

for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
 
for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap