1.顺序不重要 在容器中持有一组数据,在需要时拿出来 这就要用字典
2.键必须是唯一的
3.Swift 中Dictionary 类型的键必须可散列也就是每个key必须提供一种机制让Dictionary保证任何给定的键都是唯一的
4.声明Dictionary实例
vardict1:Dictionary=[:] ->创建Dictionary空实例,提供的类型约束键和值
vardict2=Dictionary() 默认初始方法 准备一个空的字典实例
vardict3:[String:Double]=[:]
vardict4=[String:Double]()
5.输出键值对的个数
varmovieRatings = ["Donnie Darko":4,"Chungking Express":5,"Dark City":4]
print(movieRatings.count)
6.用键取值
letdarkRating =movieRatings["Donnie Darko"]
//darkRating类型是int?但movieRatings是[String: Int]中的值Int
为什么?
因为这时候darkRating还没有赋值。类型为Int?并且被置为nil
7.更新值
(1)movieRatings["Dark City"] =5
movieRatings
(2)//updateValue(_:forKey:)
//更新的值,哪个键对应的值要更新
//这个方法之所以有用,它能保存更新之前该键所对应的值
letoldRating:Int? =movieRatings.updateValue(5, forKey:"Donnie Darko")
ifletlastRating =oldRating,letcurrentRating =movieRatings["Donnie Darko"] {
print("Old rating:\(lastRating); current rating:\(currentRating)")
}
8.增加键值对
movieRatings["The Cabinet of Dr. Caligari"] =5
9.键作为参数,删除键值对
(1)movieRatings.removeValue(forKey:"Dark City")
(2)
//let removedRating: Int? = movieRatings.removeValue(forKey: "Dark City")
//与更新类似可以返回一个被删除的实例的可空类型赋值给可空类型的常量
(3)
movieRatings["Dark City"] =nil
//不会返回被删除键的值
10.循环字典
//Swift的Dictionary类型为遍历实例中的每个元素的键值对提供了一个方便的机制,这种机制通过表示键和值的临时常量把每个元素作为组成部分.这些常量放在一个元祖中,for-in循环可以在循环体内访问
//(1)循环遍历键值
for(key, value)inmovieRatings{
print("The movie\(key) was rated\(value).")
}
//(2)循环便利键
formovieinmovieRatings.keys{
print("User has rated\(movie).")
}
11.创建不可变数组
letalbum = ["Diet Roast Beef":268,
"Dubba Dubbs Stubs His Toe":467,
"Smokey's Carpet Cleaning Service":187,
"Track 4":221]
album
12.把字典转换为数组
letwatchedMovies =Array(movieRatings.keys)