swift 学习

Swift 8、字典的使用

2019-09-27  本文已影响0人  KYM1988

import UIKit

// 1、 定义字典

// 1.1 let 修饰 不可变字典

// OC --write--> let dict = @{@"name":@"wah"}

// 系统会自动判断后面的【】中存放的键值对,还是一个一个的元素

// let dict:Dictionary = ["name":"huangLL","age":29,"height":1.55]

let dict = ["name":"huangLL","age":29,"height":1.55] as [String : Any]

//-----------------------------------------------------------

// 1.2 var 修饰 可变字典

//var dictM = Dictionary()

//var dictM = [String : NSObject]()

var dictM = [String : AnyObject]()

// 2、对可变字典的基本操作

// 2.1 添加元素

dictM["name"]  = "KK" as AnyObject?

dictM["age"]    = 29  as AnyObject?

dictM["height"] = 1.88 as AnyObject?

dictM["weight"] = 70  as AnyObject?

// 2.2 删除元素

dictM.removeValue(forKey: "weight")

dictM

// 2.3 修改元素

// 区别:如果字典已经有相对的key,那么会直接修改原来key中保存的value

// 如果字典中没有对应的key,那么添加对应的key/value

dictM["name"] = "ll" as AnyObject?

dictM

// 2.4 获取某一个元素

dictM["age"]

//-----------------------------------------------------------

// 3、遍历字典

// 3.1 遍历字典中所有的key

for key in dictM.keys{

print(key)

}

// 3.2 遍历字典中所有的values

for value in dictM.values{

print(value)

}

// 3.3 遍历字典所有的键值对

for (key1,value1) in dictM {

print(key1)

print(value1)

}

//-----------------------------------------------------------

// 4、合拼字典

// 即使类型一致也不能相加合拼

var dict1 = ["name":"007","age":28] as [String : Any]

let dict2 = ["height":1.88,"phine":"00000000"] as [String : Any]

for (key,value) in dict2 {

dict1[key] = value

}

dict1

上一篇下一篇

猜你喜欢

热点阅读