//字典 //声明 //1.泛型语法声明 @H_301_8@var myDict : Dictionary<String,String> //2.使用简化语法声明 @H_301_8@var dictText : [String:Int] @H_301_8@var dictText1 : [String:String] //赋值 //1.创建一个字典结构体,使用默认的参数 myDict = Dictionary<String,String>() println(myDict)//[:] dictText = Dictionary<String,Int>(minimumCapacity: 5) println(dictText) //2.使用简化语法创建字典 dictText1 = ["high":"20","fat":"110"] println(dictText1)//[fat: 110,high: 20] //创建不包含任何key-value对的字典 @H_301_8@var emptyDic : [String:Double] = [:] //isEmpty属性可判断数组,字典是否不包含任何元素 println(emptyDic.isEmpty) //true @H_301_8@var em : [String:String] em = Dictionary() println(em.isEmpty) //字典的使用 @H_301_8@var high = dictText1["high"] println(high)//Optional("20") //访问不存在的key返回nil @H_301_8@var tro = dictText1["tro"] println("\(tro)")//nil //修改指定的key对应的value dictText1["fat"] = "200" println(dictText1)//[fat: 200,high: 20] //如果key不存在,则添加 dictText1["pressure"] = "112" println(dictText1)//[fat: 200,high: 20,pressure: 112] //如果需要返回key对应的value需要加“!”强制解析 @H_301_8@var englis : String? = dictText1["high"] @H_301_8@if englis != nil { println(englis!) }@H_301_8@var result = dictText1.updateValue("289",forKey: "fat") println("result is \(result)")//result is Optional("200") println(dictText1)//[fat: 289,pressure: 112] /** for in遍历字典 */ @H_301_8@var seasons = ["a":"测试","b":"summer","c":"autumn"] /** * b:summer a:测试 c:autumn */ @H_301_8@for (season,desc) in seasons { println("\(season):\(desc)") } /** 单独使用字典的keys和values */ @H_301_8@var keys = Array(seasons.keys) @H_301_8@var valuess = Array(seasons.values) println("\(keys)....\(valuess)")//[b,a,c]....[summer,测试,autumn] //删除 seasons.removeValueForKey("d") /** [b: summer,a: 测试,c: autumn] */ println(seasons) seasons.removeValueForKey("c") //[b: summer,a: 测试] println(seasons) //通过将value赋值为nil来删除 seasons["b"] = nil println(seasons)//[a: 测试]
部分内容来自于<疯狂Swift讲义>
总结以上是内存溢出为你收集整理的Swift学习笔记-字典Dictionary全部内容,希望文章能够帮你解决Swift学习笔记-字典Dictionary所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)