iOS Array和Dictionary常用方法 发表于 2016-01-28 | 分类于 ios iOS Array和Dictionary常用方法 Dictionary的常用方法代码 1234567891011121314151617181920212223242526272829303132333435//创建var dic:[String:String] = [:];//赋值dic["22"] = "222";dic["bb"] = "bbb";dic["33"] = "333";dic["11"] = "111";dic["aa"] = "aaa";print("\n赋值dic:\n\(dic)");print("\n遍历获取下标key:");for (index, element) in dic.enumerate() { print("Item \(index): \(element)")}//key的数组let keySet = Array(dic.keys);print("\nkey的数组keySet:\n\(keySet)");//key数组升序排列let keyNew = keySet.sort { (a, b) -> Bool in return a < b;}print("\nkey数组升序排列keyNew:\n\(keyNew)");//dic按key的升序排列var dicNew = dic.sort { (a, b) -> Bool in return a.0 < b.0;}print("\ndic按key的升序排列dicNew:\n\(dicNew)");//移除dicNew.removeFirst()print("\n移除dicNew:\n\(dicNew)"); 控制台输出 123456789101112131415161718192021赋值dic:["22": "222", "11": "111", "aa": "aaa", "bb": "bbb", "33": "333"]遍历获取下标key:Item 0: ("22", "222")Item 1: ("11", "111")Item 2: ("aa", "aaa")Item 3: ("bb", "bbb")Item 4: ("33", "333")key的数组keySet:["22", "11", "aa", "bb", "33"]key数组升序排列keyNew:["11", "22", "33", "aa", "bb"]dic按key的升序排列dicNew:[("11", "111"), ("22", "222"), ("33", "333"), ("aa", "aaa"), ("bb", "bbb")]移除dicNew:[("22", "222"), ("33", "333"), ("aa", "aaa"), ("bb", "bbb")] Array的常用方法代码 12345678910111213141516171819202122232425262728293031//创建var arr:[String] = [];//赋值arr.append("111");arr.append("bbb");arr.append("aaa");print("\n赋值arr:\n\(arr)");//排序let reverseArr = arr.reverse();print("\n排序reverseArr:\n\(reverseArr)");//逆向后遍历print("\n逆向后遍历key:");for key in reverseArr{ print("\(key)");}print("\n逆向后遍历获取下标key:");for (index, element) in reverseArr.enumerate() { print("Item \(index): \(element)")}//移除arr.removeFirst()print("\n移除arr:\n\(arr)");//范围移除arr.removeRange(Range(start:0,end:1))print("\n范围移除arr:\n\(arr)"); 控制台输出 123456789101112131415161718192021赋值arr:["111", "bbb", "aaa"]排序reverseArr:ReverseRandomAccessCollection<Array<String>>(_base: ["111", "bbb", "aaa"])逆向后遍历key:aaabbb111逆向后遍历获取下标key:Item 0: aaaItem 1: bbbItem 2: 111移除arr:["bbb", "aaa"]范围移除arr:["aaa"]