//: Playground - noun: a place where people can play import UIKit //----字典的使用------// //字典是一种存储多个相同类型的元素的容器 //每个值都关联着一个键,键作为字典中存储数据标识 //字典是无序的 //字典的限制:keyType必须是可哈希的(Hashable),提供一个哈希值让这个key可以被识别。 //1.字典的创建 var books : Dictionary<String, Int> = ["西游记": 40, "三国演义":45, "红楼梦": 80] var books2 = ["西游记": 40, "三国演义":45, "红楼梦": 80] //空字典 var names1 : Dictionary<String, Int> = Dictionary() var names2 : Dictionary<String, Int> = [:] var names3 = [String : Int]() var names4 = Dictionary<String, Int>() var names5 : [String : Int] = [:] //2.键值对的个数 books.count //3.查找出某个key对应的值 let price = books["西游记"] let price2 = books["Jobs"] //如果字典中没有查找的key,则返回nil //4.修改数据 books["西游记"] = 50 //下标操作返回的是修改之后的值 print(books) books.updateValue(150, forKey: "西游记") //update操作返回的是修改之前的旧值 print(books) books["Jobs"] = 1000 //如果key不存在,则会创建一个新的键值对并添加到字典中 print(books) //5.遍历字典 for (key, value) in books { print("(\(key):\(value))"); } //只遍历key let keyArray = books.keys for key in keyArray { print(key) } let valueArray = books.values for value in valueArray { print(value) }
时间: 2024-11-05 21:43:52