Swift字典用来存储无序的,相同类型的数据的集合。Swift字典会自动检测元素的类型,如果不同,则会报错。字典的每个值(value)都会关联唯一的一个键(key),键作为字典中的这个值数据的标识符。Swift字典的key没有类型限制,可以是整型或者字符串,但必须是唯一的。
字典创建
var dict = ["panda":"大熊猫", "dog":"狗", "eagle":"鹰", "pigeon":"鸽子"]
//也可以声明字典的键值类型
//var dict: [String:String]
//var dict: Dictionary<String, String>
创建空字典
var emptyDictionary:[String:Int] = [:]
var emptyDictionary:Dictionary<Int,String> = [:]
var emptyDictionary = [String:String]()
var emptyDictionary = Dictionary<Int,Int>()
字典的访问
dict["panda"] //"大熊猫"
if let value = dict["panda"] {
print("panda 的意思是 - \(value)")
}
获取键值对的数量
dict.count //4
判空
dict.isEmpty //false
获取字典中的所有键/值
dict.keys
dict.values
Array(dict.keys) //["panda", "eagle", "dog", "pigeon"]
Array(dict.values) //["大熊猫", "狗", "鹰", "鸽子"]
遍历
for key in dict.keys {
print(key)
}
for (key, value) in dict {
print("\(key) : \(value)")
}
for (key, value) in dict.enumerate() {
print("字典 key \(key) - 字典 (key, value) 对 \(value)")
}
比较,当两个字典所有键值对均相同时,则两个字典相等
var dic1 [Int:String] = [1:"A", 2:"b"]
var dic2 Dictionary<Int:String> = [2:"b", 1:"A"]
dic2 == dic1 //true
添加键值对
dict["mouse"] = "老鼠"
dict.updateValue("狐狸", forKey: "fox")
//["panda":"大熊猫", "fox":"狐狸", "dog":"狗", "eagle":"鹰", "pigeon":"鸽子", "mouse":"老鼠"]
修改值
dict["fox"] = "欺骗"
dict.updateValue("鼠标", forKey: "mouse")
//["panda":"大熊猫", "fox":"欺骗", "dog":"狗", "eagle":"鹰", "pigeon":"鸽子", "mouse":"鼠标"]
删除键值对
dict["fox"] = nil
dict.removeValue(forKey: "dog")
//["panda":"大熊猫", "eagle":"鹰", "pigeon":"鸽子", "mouse":"鼠标"]
dict.removeAll() //移除所有键值对
网友评论