Swift字典

2018-01-10  本文已影响0人  qtoq126
  1. 字典的初始化
var dict = ["Swift":"雨燕,快速的", "Python":"大蟒", "Java":"爪哇岛,咖啡", "Ruby":"钻石"]

var emptyDictionary1: [String:Int] = [:]
var emptyDictionary2: Dictionary<String,Int> = [:]
var emptyDictionary3 = [String:Int]()
var emptyDictionary4 = Dictionary<String,Int>()
  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"] = "imooc@imooc.com"
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("警告:修改后的密码跟之前密码一样!")
}
上一篇下一篇

猜你喜欢

热点阅读