栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Swift 字典 Dictionary 集合类型

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Swift 字典 Dictionary 集合类型

Swift 字典 Dictionary 集合类型

Dictionary 字典集合类型。类似于 Java 的 map。特点:键唯一,值可重复

1. 创建字典
// 创建空字典
var emptyDict1: [Int : String] = [:]
var emptyDict2: Dictionary = Dictionary()

// 指定键值类型
var dict: [Int : String] = [0: "Zero", 1: "One", 2: "Two"]
var dict2: Dictionary = Dictionary(dictionaryLiteral: (1, "One"), (2, "Two"))

// 自动推断键值类型
var dictAuto = [0: "Zero", 1: "One", 2: "Two"]

2. 获取元素
// 获取元素个数
dict.count // 3

// 判断字典为空
dict.isEmpty // false

// 获取键对应的值
dict[1] // One

3. 更新键值对
// 修改键对应的值
dict[0] = "000" // 000

// 如果键存在,就更新,否则就新增键值对
dict[-1] = "-1" // -1

// 更新键对应的值,如果键不存在,返回 nil
if let lastValue = dict.updatevalue("new one", forKey: 1) {
    print("the last value is (lastValue)") // the last value is One
}

// 移除键值对
dict.removevalue(forKey: -1) // -1

// 移除所有键值对
//dict.removeAll()

4. 遍历字典
// dict [1: "new one", 2: "Two", 0: "000"]

// 遍历字典的键
for ele in dict.keys {
    print(ele)
}

// 遍历字典的值
for ele in dict.values {
    print(ele)
}

// 元组遍历,直接获取键值对
for (key, val) in dict {
    print("(key):(val)")
}

// 对 key 进行从小到大排序后遍历,并对值进行拆包
for ele in dict.keys.sorted(by: <) {
    print(dict[ele]!)
}
GitHub 源码:DictionaryType.playground
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446229.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号