Swift学习笔记(6)--字典
1.定义
//1.基本定义 [key 1: value 1, key 2: value 2, key 3: value 3] var dict = ["name":"Xiaoqin","sex":"female","age":"20"] for (key,value) in dict { println(key,value) } //2.类型强制定义 Dictionary<keyType,valueType> var dict2:Dictionary<Int,String>=[1:"Beijing",2:"Nanjing"] for (key,value) in dict2 { println(key,value) } //3.空字典 var namesOfIntegers = Dictionary<Int, String>() // namesOfIntegers 是一个空的 Dictionary<Int, String> //4.根据上下文使用[:]重新创建空字典 namesOfIntegers[16] = "sixteen" // namesOfIntegers 现在包含一个键值对 namesOfIntegers = [:] // namesOfIntegers 又成为了一个 Int, String类型的空字典
2.数据项总数:count
var airports = ["TYO": "Tokyo", "DUB": "Dublin"] println("The dictionary of airports contains \(airports.count) items.") // 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
2.读取和修改字典
//1.使用key值来添加和修改数据项 // 1.1添加 airports["LHR"] = "London" // 1.2修改 airports["LHR"] = "London Heathrow" //2.使用updateValue(forKey:)函数来添加或者修改值 // 2.1添加 airports.updateValue("Beijing", forKey: "BJ") // 2.2修改 airports.updateValue("Bei Jing", forKey: "BJ")
注:1.updateValue(forKey:)函数会返回包含一个字典值类型的可选值。举例来说:对于存储String值的字典,这个函数会返回一个String?或者“可选 String”类型的值。如果值存在,则这个可选值值等于被替换的值,否则将会是nil
2.我们也可以使用下标语法来在字典中检索特定键对应的值。由于使用一个没有值的键这种情况是有可能发生的,可选类型返回这个键存在的相关值,否则就返回nil
:
//1.updateValue返回值为原值 if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") { println("The old value for DUB was \(oldValue).") //Dublin } //2.key没有对应的value时返回nil,使用可选值optional做判断 if let airportName = airports["DUC"] { println("The name of the airport is \(airportName).") } else { println("That airport is not in the airports dictionary.") }
3.删除元素
var airports = ["TYO": "Tokyo", "DUB": "Dublin", "BJ": "Beijing"] //1.直接设置为nil airports["DUB"] = nil // DUB现在被移除了 //2.使用removeValueForKey函数删除key对应的字典项 airports.removeValueForKey("BJ")
注:removeValueForKey方法也可以用来在字典中移除键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的value或者在没有值的情况下返回nil
var airports = ["TYO": "Tokyo", "DUB": "Dublin", "BJ": "Beijing"] if let removedValue = airports.removeValueForKey("SH") { println("The removed airport's name is \(removedValue).") } else { println("The airports dictionary does not contain a value for SH.") //此句被打印 }
4.遍历
var airports = ["TYO": "Tokyo", "DUB": "Dublin"] //1.键值对统一遍历 for (airportCode, airportName) in airports { println("\(airportCode): \(airportName)") } //2.key和value分别遍历 for airportCode in airports.keys { println("Airport code: \(airportCode)") } for airportName in airports.values { println("Airport name: \(airportName)") }
5.转换为数组
如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受Array
实例 API 的参数,可以直接使用keys
或者values
属性直接构造一个新数组
var airports = ["TYO": "Tokyo", "DUB": "Dublin"] let airportCodes = Array(airports.keys) println(airportCodes) //[DUB, TYO] let airportNames = Array(airports.values) println(airportNames) //[Dublin, Tokyo]