Swift-字典

// 创建空字典
var emptyDict = [Int: String]()

// 或者
emptyDict = Dictionary<Int, String>()

// 当创建过emptyDict后,再用[:]又成为一个空字典
emptyDict = [:]


//初始化
// 多个键值对用逗号分割
// 通过类型推断是可以推断出来类型为[String: String]
var dict = ["A": "Apple", "B": "Bubble"]

// 手动指明数据类型
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]


//声明不可变字典
// 如果不希望字典可变,用let声明即可
let immutableDict = ["A": "Apple", "B": "Bubble"]
// 无法调用,因为是不可变的
//immutableDict.updateValue("App", forKey: "A")
//immutableDict += ["AB:", "Apple Bubble"]

//判断字典
if dict.isEmpty {
  print("dict is an empty dictionary")
} else {
  print("dict is not an empty dictionary")
}

// 或者通过获取字典元素的个数是否为0
if dict.count == 0 {
  print("dict is an empty dictionary")
} else {
  print("dict is not an empty dictionary")
}

// 通过key直接获取
var apple = dict["A"]

// 获取索引获取(key, value),再获取值
// 由于字典中的(key, value)是元组,因此可以直接通过点语法获取
let startKeyValue = dict[dict.startIndex]
let value = startKeyValue.1

// 读取时,判断是否有值
if let value = dict["BB"] {
  print("value is \(value)")
} else {
  // 输入这行
  print("The key BB doesn\'t not exist in dict")
}

// 修改,如果不存在,则会增加,否则更新值
dict["A"] = "Good Apple"

// 或者用API,如果不存在,则会增加,否则只是更新值
if let oldValue = dict.updateValue("Dog", forKey: "D") {
  print("The old value is \(oldValue)")
} else {
  // 输出这行
  print("The key D does\'t not exist before update")
}

// 通过下标语法移除元素
dict["D"] = nil

// 或者通过调用removeValueForKey方法来移除
if let removedValue = dict.removeValueForKey("D") {
  print("The removed value is \(removedValue)")
} else {
  print("The key D doesn'\t exist in dict, can\' be removed.")
}

// 或者清空字典:
dict.removeAll()

遍历字典

1.遍历所有的key

for key in dic.keys{

print(key)

}

2.遍历所有值

for value in dic.values{

print(value)

}

3.遍历所有的键值对

for (key,value) in dic{

print(key)

print(value)

}

字典的合并

即使类型一致也不能相加合并

for (key,value) in dic2{

dic1[key] = value

}

 

posted @ 2016-08-31 16:40  J-Vijay  阅读(177)  评论(0)    收藏  举报