swift从入门到精通1.3-Dictionary

2,207 阅读2分钟

1.定义字典

var dic1 = [String:Any]()
var dic2 = Dictionary<String,Any>()
var dic3:[String:Any] = [:]

2.初始化字典

//初始化字典
var dic4 = ["A": 123, "B": 456, "C": 789]
var dic5: [String: Int] = ["A": 123, "B": 456, "C": 789]

3.添加数据

//添加数据
var testDic = ["A": 123, "B": 456, "C": 789]
testDic["D"] = 250

4.修改数据

//修改数据
testDic.updateValue(290, forKey: "E")

5.查询数据

//查询数据
print(testDic["E"] ?? 0)
print(testDic["F"] as Any)

6.删除数据

//删除数据
//无序的,不像数组,不建议通过下标删除,有点随机性
testDic.remove(at: testDic.startIndex)
testDic.remove(at: testDic.index(testDic.startIndex, offsetBy: 1))
testDic.removeValue(forKey: "A")
testDic.removeAll()

7.获取长度

//长度
print(testDic.count)

8.判断是否为空

//是否为空
print(testDic.isEmpty)

9.获取key和value的数组

//获取key和value的数组
print(testDic.keys)
print(testDic.values)

10.遍历字典

//遍历字典
for (key,value) in testDic {
    print(key,value)
}


for item in testDic {
    print("item:",item.key,item.value)
}


for index in testDic.enumerated() {
    print("index:",index.offset,index.element.key,index.element.value)
}

11.json字符串转字典

//json字符串转字段
func getDicFromJsonStr(jsonString: String) -> NSDictionary {
    let jsonData:Data = jsonString.data(using: .utf8)!
    let dic = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
    if dic != nil {
      return dic as! NSDictionary
    }else {
        return NSDictionary()
    }
}

12.Filter(刷选数据)

//刷选数据
var filterDic = testDic.filter { (key,value) -> Bool in
    value > 300
}
//简写 ["C": 789, "B": 456]
var filterDic2 = testDic.filter{$1 > 300}

13.Map(映射数据)

//映射数据
testDic = ["A": 123, "B": 456, "C": 789]
//["D": 500, "A": 246, "E": 580, "C": 1578, "B": 912]
var mapDic = testDic.mapValues { (value) -> Int in
    value * 2
}


//[750, 369, 870, 2367, 1368]
var mapDic2 = testDic.map { (key,value) -> Int in
    value * 3
}


//[("Bz", 912), ("Cz", 1578), ("Az", 246)]
var mapDic3 = testDic.map { (key,value) -> (String,Int) in
    (key+"z",value * 2)
}


上篇文章:swift从入门到精通1.1-String

中篇文章:swift从入门到精通1.2-Array

下篇文章:swift从入门到精通1.3-Dictionary