Swift字典

  1. 字典的初始化
var dict = ["Swift":"雨燕,快速的", "Python":"大蟒", "Java":"爪哇岛,咖啡", "Ruby":"钻石"]

var emptyDictionary1: [String:Int] = [:]
var emptyDictionary2: Dictionary = [:]
var emptyDictionary3 = [String:Int]()
var emptyDictionary4 = Dictionary()
  1. 字典的成员变量
dict["Swift"] //可选型,通过键找值
dict.count
emptyDictionary1.isEmpty
Array(dict.keys)
Array(dict.values)
  1. 遍历
//遍历键
for key in dict.keys {
    print(key)
}
//遍历键值
for(key,value) in dict {
    print("\(key) : \(value)")
}
//字典比较
let a = [1:"A", 2:"B", 3:"C"]
let b = [1:"A", 3:"C", 2:"B"]
a == b // true
  1. 数组的增删改查
var user = ["name":"zhenzhen", "password":"qinzhen", "occupation":"programmer"]
//增
user["e-mail"] = "[email protected]"
user.updateValue("imooc.com", forKey: "Website")
//删
user["e-mail"] = nil //给键直接赋空值
user.removeValue(forKey: "password") //返回值是所删除的值
if let email = user.removeValue(forKey: "password") {
  print("电子邮箱 \(email) 已删除成功")
}
//改
user["occupation"] = "freelancer"
user.updateValue("Imooc", forKey: "password") //返回值是所删除的键对应的值(旧值)
if let oldPassword = user.updateValue("Imooc", forKey: "password") , 
    let newPassword = user["password"], oldPassword == newPassword {
      print("警告:修改后的密码跟之前密码一样!")
}

你可能感兴趣的:(Swift字典)