swift 字典

  1. 创建一个空字典
var enpty = [String: Int]()

2.声明一个字典

var myDic = ["name":"xingweixin","age":"27"]

3.添加或者修改valye值

myDic["address"] = "beijing"

4.删除age这个字段

myDic.removeValue(forKey: "age")

5.删除name字段

myDic["name"] = nil;

6.访问字典key的合集

let keys = myDic.keys

7.访问字典value的合集

let values = myDic.values

8.遍历字典

var dict = ["user":"xingweixin","logon":"cgac","hgflag":"lt"]
for (key,value) in dict {
    print("\(key)是\(value)")
}

9.过滤元素

var age1 = ["xing":27,"liu":28,"huang":30]
var age2 = age1.filter{$0.value < 29}  //["xing": 27, "liu": 28]

10.通过元组创建字典

let tupleArray = [("Monday", 30),  ("Tuesday", 25),  ("Wednesday", 27)]
let dictionary = Dictionary(uniqueKeysWithValues: tupleArray)
print(dictionary) //["Monday": 30, "Tuesday": 25, "Wednesday": 27]

11.通过键值序列创建字典

let names = ["Apple", "Pear"]
let prices = [7, 6]
let dictx = Dictionary(uniqueKeysWithValues: zip(names, prices)) //["Pear": 6,  "Apple": 7]

12.只有键序列、或者值序列创建字典

let array = ["Monday", "Tuesday", "Wednesday"]
let dict1 = Dictionary(uniqueKeysWithValues: zip(1..., array))
let dict2 = Dictionary(uniqueKeysWithValues: zip(array, 1...))
print(dict1) //[1: "Monday", 2: "Tuesday", 3: "Wednesday"]
print(dict2) //["Monday": 1, "Tuesday": 2, "Wednesday": 3]

你可能感兴趣的:(swift 字典)