Swift3.0 - 字典

Swift3.0 - 真的很简单
Swift3.0 - 数据类型
Swift3.0 - Array
Swift3.0 - 字典
Swift3.0 - 可选值
Swift3.0 - 集合
Swift3.0 - 流控制
Swift3.0 - 对象和类
Swift3.0 - 属性
Swift3.0 - 函数和闭包
Swift3.0 - 初始化和释放
Swift3.0 - 协议protocol
Swift3.0 - 类和结构体的区别
Swift3.0 - 枚举
Swift3.0 - 扩展
Swift3.0 - 下标
Swift3.0 - 泛型
Swift3.0 - 异常错误
Swift3.0 - 断言
Swift3.0 - 自动引用计数(strong,weak,unowned)
Swift3.0 - 检测API
Swift3.0 - 对象的标识
Swift3.0 - 注释
Swift3.0 - 元类型
Swift3.0 - 空间命名
Swift3.0 - 对象判等
Swift3.0 - 探究Self的用途
Swift3.0 - 类簇
Swift3.0 - 动态调用对象(实例)方法
Swift3.0 - 文本输出
Swift3.0 - 黑魔法swizzle
Swift3.0 - 镜像
Swift3.0 - 遇到的坑

基本

  • 创建
var namesOfIntegers = [Int: String]()
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
  • 赋值,修改值
namesOfIntegers[16] = "sixteen"
airports["LHR"] = "London Heathrow"

 // 更新值返回久的值,值可能为nil
 if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \\(oldValue).")
}
if let x = dic[1]{
print(x)
}
  • 清空
namesOfIntegers = [:]
  • 检测是否为空
if airports.isEmpty {}
  • 移除值
dic[1] = nil
dic.removeValue(forKey: 1)
  • 遍历值
for (airportCode, airportName) in airports {
    print("\\(airportCode): \\(airportName)")
}
for airportCode in airports.keys {
   print("Airport code: \\(airportCode)")
}
for airportName in airports.values {
   print("Airport name: \\(airportName)")
}

中级

  • 字典存储方式是乱序的
var dic = [1:"23",3:"3"]
dic.remove(at: dic.index(dic.startIndex, offsetBy: 1))
print(dic)

运行:

[3: "3"]

  • 怎么将字典的keys或者values放入数组中
  let keys = [Int](dic.keys)
  let values = [String](dic.values)

提示:

let keys = dic.keys 获取的不是数组,但是可以通过for...in遍历它里面的元素

推荐阅读更多精彩内容