Swift基础 Dictionary字典

字典

字典和数组都是集合类型,字典元素可以是值类型也可以是引用类型。
键名不允许重复。

字典的声明方式(三种)

显式:
    var studentList : Dictionary<String,Float> = ["xiaoMing":172.5,"xiaoHong":168.5]
    //以键值对的形式遍历
    for (name,height) in studentList {
    
    
        print("\(name):\(height)");
    }

运行结果:

xiaoMing:172.5
xiaoHong:168.5
隐式:
    var studentList : [String:Float] = ["xiaoMing":172.5,"xiaoHong":168.5]
    for (name) in studentList.keys {
    
    
        print("key:\(name)");
    }

运行结果:

key:xiaoHong
key:xiaoMing
简略:
    var studentList = ["xiaoMing":172.5,"xiaoHong":168.5]
    for (height) in studentList.values {
    
    
        print("value:\(height)");
    }

运行结果:

value:172.5
value:168.5
快捷声明:
var occupations = [:]
取值:
var studentList = ["xiaoMing":172.5,"xiaoHong":168.5]
print(studentList["xiaoMing"] ?? "unknown")
更新:
var studentList = ["xiaoMing":172.5,"xiaoHong":168.5]
studentList.updateValue("xiaoHua", forKey:155.0)
//如果studentList里面有xiaoHua则会更新上,
//如果没有xiaoHua则会加上去
删除:
var studentList = ["xiaoMing":172.5,"xiaoHong":168.5]
studentList.removeValue(forKey: "xiaoMing")

合并

错误写法:dic1+dic2
由于两个字典里面可能会有相同的键名,所以在加的时候,无法对相同键名的值进行取舍,所以不能简单粗暴地使用+语法。

对于这样的合并需求,只能乖乖进行遍历合并。

let studentHeightList = ["xiaoMingHeight":172.5,"xiaoHongHeight":168.5]
let studentAchievementList = ["xiaoMingAchievement":355.0,"xiaoHongAchievement":384.0]

//错误示范:let studentInfo = studentHeightList + studentAchievementList

var studentInfo = studentHeightList
for (key,value) in studentAchievementList {
    
    
    studentInfo[key] = value
}

print(studentInfo)

运行结果:

["xiaoMingAchievement": 355.0, "xiaoHongHeight": 168.5, "xiaoMingHeight": 172.5, "xiaoHongAchievement": 384.0]

猜你喜欢

转载自blog.csdn.net/kkkenty/article/details/124606965