import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//定义
func demo1() {
//定义字典
let dict = ["name":"张","age":"12"]
print(dict)
//定义字典数组 这种形式在开发中使用很多
let array: [[String: AnyObject]] = [
["name":"张" as AnyObject,"age":"12" as AnyObject],
["name":"张" as AnyObject,"age":"12" as AnyObject]
]
print(array)
}
//遍历
func demo2() {
func demo() {
var dict = ["name":"张","age":"12"]
//遍历方式一
for e in dict{
//e: (key: String, value: String) 这是一个元组
print("\(e.key)\(e.value)")
}
//遍历方式二
//前面是key 后面是value 具体名字可随意更改
for (k,v) in dict{
print("\(k)\(v)")
}
}
}
//增删改
func demo3() {
var dict = ["name":"张","age":"12"]
//如果key存在就是修改,不存在就是增加
//增
dict["sex"] = "男"
//改
dict["name"] = "李"
//删,直接给定key即可
// 科普:字典是通过KEY来定位的,KEY必须是可以 ’hash 哈希‘的 MD5一样
// hash就是讲字符串变成唯一的数字,便于查找,提高效率
dict.removeValue(forKey: "age")
print(dict)
dict.removeAll()
}
// 合并
func demo4() {
func demo() {
var dict1 = ["name":"张","age":"12"]
let dict2 = ["name":"李","age":"23"]
//提示:字典不能像数组那样直接用+
//思路:遍历dict2 依次设置
for e in dict2{
//如果key不存在,直接增加。存在的话就会更改。
dict1[e.key] = dict2[e.key]
}
print(dict2)
}
}
}
网友评论