Swift 字典 Dictionary基本用法

前端之家收集整理的这篇文章主要介绍了Swift 字典 Dictionary基本用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


import UIKit

/*
 字典的介绍
 1.字典允许按照某个键访问元素
 2.字典是由两部分组成,一个键(key)集合,一个是值(value)集合
 3.键集合是不能有重复的元素,值集合可以有重复的元素,键和值是成对出现的
 4.Swift 字典类型是Dictionary 也是一个泛型集合
 5.字典分为  可变字典和 不可变字典
 let 修饰不可变字典   var修饰可变字典
 */


//1.定义字典
//1>定义不可变字典
//OC   @{@"name":@"summer",@"age":@18}
//系统会自动判断后面[]中存放的键值对,还是一个一个元素
let dict = ["name" : "summer","age" : 18,"height" : 1.88] as [String : Any]

//2>定义可变字典
//var mutableDict = Dictionary<String,NSObject>() //方式一
//AnyObject: 一般指定类型  NSObject: 一般用于创建对象
//var mutableDict = [String : NSObject]()   //方式二
var mutableDict = [String : AnyObject]() //常用  方式三

//2.对可变字典的基本操作(增删改查)
//2.1> 添加元素
mutableDict["name"] = "summer" as AnyObject?
mutableDict["age"] = 18 as AnyObject?
mutableDict["height"] = 1.88 as AnyObject?
mutableDict["weight"] = 60 as AnyObject?
mutableDict
//2.2> 删除元素
mutableDict.removeValue(forKey: "age")
mutableDict
//2.3>修改元素
//  区别:如果字典中已经有了对应的key,那么会直接修改原来key中保存的value
//  如果字典中没有对应的key,那么添加对应的key/value
mutableDict["name"] = "sun" as AnyObject?
mutableDict
mutableDict ["sex"] = "女" as AnyObject?
mutableDict
//2.4> 获取某一个元素
mutableDict["sex"]

//3.遍历字典
//3.1>遍历字典中所有的key
for key in mutableDict.keys{
    print(key)
}
//3.2>遍历字典中所以的值
for value in mutableDict.values{
    print(value)
}
//3.3>遍历所有的键值对
for (key,value) in mutableDict{
    print(key)
    print(value)
}

//4.字典的合并
//即使类型一致也不能相加进行合并
//let dict1 = ["name":"summer","age" : 18] as [String : Any]
//let dict2 = ["sex" : "男","phoneNumber" : "+86 0393"] as [String : Any]
//
//let resultDict = dict1 + dict2  //写法是错误的

//如果必须合并  那么只能
var dict1 = ["name":"summer","age" : 18] as [String : Any]
let dict2 = ["sex" : "男","phoneNumber" : "+86 0393"] as [String : Any]

for (key,value) in dict2{
    dict1[key] = value as AnyObject?
}
dict1



猜你在找的Swift相关文章