系统: Mac OS 10.15.2, XCode 11.3,swift 5.0
写作时间:2020-01-08

说明

Dictionary为字典键值对,是比较常用的容器,初始化的格式如下。

var someDict = [KeyType: ValueType]()

Creating Dictionary

创建可以一个空的容器,或者初始化为指定的值

var dict = [Int: String]()
var dict1:[Int: String] = [1:"One", 2:"Two", 3:"Three"]

Sequence Based Initialization

通过key数组, Value数组,创建字典。

var cities = ["Delhi", "Bangalre", "Hyderabad"]
var distance = [2000, 10, 620]
let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, distance))

Filtering

通过过滤掉不符合条件的子项。

var closeCities = cityDistanceDict.filter{ $0.value < 1000 }
print("\(closeCities)")
// closeCities > ["Bangalore": 10, "Hyderabad": 620]

Dictionary Grouping

给字典分组,下面为对第一个字符相同的子项划分为同一组。

var city = ["Delhi", "Bangalore", "Hyderabad", "Dehradun", "Bihar"]
var GroupedCities = Dictionary(grouping: city) { $0.first! }
print("\(GroupedCities)")
// ["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]

Accessing Dictionaries

方位字典的value通过key值索引获取
var someVar = someDict[key]

var someDict:[Int: String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]print("Value of key = 1 is \(someVar)")
print("Value of key = 2 is \(someDict[2])")
print("Value of key = 3 is \(someDict[3])")
//Value of key = 1 is Optional("One")
//Value of key = 2 is Optional("Two")
//Value of key = 3 is Optional("Three")

Modifying Dictionaries

修改值可以通过方法updateValue, 也可以通过赋值的方式。

var oldVal = someDict.updateValue("New value of one", forKey: 1)
someVar = someDict[1]
someDict[2] = "New value of two"print("Old value of key = 1 is \(oldVal)")
print( "Value of key = 1 is \(someVar)" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )//Old value of key = 1 is Optional("One")
//Value of key = 1 is Optional("New value of one")
//Value of key = 2 is Optional("New value of two")
//Value of key = 3 is Optional("Three")

Remove Key-Value Pairs

删除键值对,可以通过方法removeValue,或者通过设置值为nil。

someDict = [1:"One", 2:"Two", 3:"Three"]
var removeValue = someDict.removeValue(forKey: 2)
someDict[3] = nil
print( "Value of key = 1 is \(someDict[1])" )
print( "Value of key = 2 is \(someDict[2])" )
print( "Value of key = 3 is \(someDict[3])" )
//Value of key = 1 is Optional("One")
//Value of key = 2 is nil
//Value of key = 3 is nil

Iterating Over a Dictionary

遍历字典正确的方式如下:

someDict = [1:"One", 2:"Two", 3:"Three"]for (key, value) in someDict {print("Dictionary key \(key) - Dictionary value \(value)")
}
//Dictionary key 3 - Dictionary value Three
//Dictionary key 1 - Dictionary value One
//Dictionary key 2 - Dictionary value Two

注意:如果遍历someDict.enumerated(),实际上得到的key为从0开始的索引,value为keyValue子项(key: 3, value: "Three")

for (index, keyValue) in someDict.enumerated() {print("index \(index) - Dictionary value \(keyValue)")
}
//index 0 - Dictionary value (key: 3, value: "Three")
//index 1 - Dictionary value (key: 1, value: "One")
//index 2 - Dictionary value (key: 2, value: "Two")

Convert to Arrays

字典的keys和values都是数组,可以单独转换为数组用. 注意转换是为数组,不是Set不重复数组,可以通过观察两个value都为Two,实际上两个Two都打印了出来。

someDict = [1:"One", 2:"Two", 3:"Two"]
let dictKeys = [Int](someDict.keys)
let dictValues = [String](someDict.values)print("Print Dictionary Keys")
for (key) in dictKeys {print("\(key)")
}print("Print Dictionary Values")
for (value) in dictValues {print("\(value)")
}
//Print Dictionary Keys
//2
//3
//1
//Print Dictionary Values
//Two
//Two
//One

The count Property

字典的数量,通过count属性来获取。

var someDict1: [Int: String] = [1:"One", 2:"Two", 3:"Three"]
var someDict2: [Int: String] = [4:"Four", 5:"Five"]
print("Total items in someDict1 = \(someDict1.count)")
print("Total items in someDict2 = \(someDict2.count)")
//Total items in someDict1 = 3
//Total items in someDict2 = 2

The empty Property

判断Dictionary是否可控,可以通过属性isEmpty来判断

var someDict3:[Int:String] = [Int:String]()
print("someDict1 = \(someDict1.isEmpty)")
print("someDict2 = \(someDict2.isEmpty)")
print("someDict3 = \(someDict3.isEmpty)")
//someDict1 = false
//someDict2 = false
//someDict3 = true

参考

https://www.tutorialspoint.com/swift/swift_dictionaries.htm

Swift 5 Dictionary用法大全相关推荐

  1. python代码大全表解释-python中的字典用法大全的代码

    如下代码是关于python中的字典用法大全的代码. #!/usr/bin/env python # # [SNIPPET_NAME: Dictionaries 101] # [SNIPPET_CATE ...

  2. python代码大全-python中的字典用法大全的代码

    如下代码是关于python中的字典用法大全的代码. #!/usr/bin/env python # # [SNIPPET_NAME: Dictionaries 101] # [SNIPPET_CATE ...

  3. python中字典的使用_python中的字典用法大全

    本文包含了python字典的各种用法,字典在python中的重要性不言而喻 #!/usr/bin/env python # # [代码名字: Dictionaries 101] # [代码分类: Py ...

  4. python 字典代码_python中的字典用法大全的代码

    标签: 如下代码是关于python中的字典用法大全的代码. #!/usr/bin/env python # # [SNIPPET_NAME: Dictionaries 101] # [SNIPPET_ ...

  5. C# MessageBox 用法大全(转)

    C# MessageBox 用法大全 http://www.cnblogs.com/Tammie/archive/2011/08/05/2128623.html 我们在程序中经常会用到MessageB ...

  6. pythonurllib模块-Python3中核心模块urllib的用法大全

    Python的urllib模块提供了一个高级的Web通信库,支持基本的协议,如HTTP.FTP和Gopher,同时也支持对本地文件的访问.在Python3中,urllib.urlparse.urlli ...

  7. MVC中HtmlHelper用法大全

    MVC中HtmlHelper用法大全参考 解析MVC中HtmlHelper控件7个大类中各个控件的主要使用方法(1) 2012-02-27 16:25 HtmlHelper类在命令System.Web ...

  8. c3p0 参数 模糊查询_MySQL模糊查询用法大全(正则、通配符、内置函数等)

    文章来源:MySQL模糊查询用法大全(正则.通配符.内置函数等) 原文作者:陈哈哈 来源平台:CSDN SELECT * from table where username like '%陈哈哈%' ...

  9. python编程字典100例_python中字典(Dictionary)用法实例详解

    本文实例讲述了python中字典(Dictionary)用法.分享给大家供大家参考.具体分析如下: 字典(Dictionary)是一种映射结构的数据类型,由无序的"键-值对"组成. ...

  10. C# ASP.NET MVC HtmlHelper用法大全

    C# ASP.NET MVC HtmlHelper用法大全 (原文) HTML扩展类的所有方法都有2个参数: 以textbox为例子 public static string TextBox( thi ...

最新文章

  1. java取geosever数据_Geoserver - 连接到SQL Server 2008 Express并获取数据
  2. SpringCloud版本说明
  3. Entity Framework Core 2.0 全局查询过滤器
  4. 33个常见问题!超全Windows排查手册
  5. amap vueamap 与_vue 使用高德地图vue-amap组件过程解析
  6. 双十一清醒指南,送3本Python书
  7. 币安选择InfStones作为以太坊2.0 Staking基础设施服务商
  8. 网络性能测试之pathrate的安装使用
  9. RX570 4G显卡怎么样?
  10. C语言实现http的下载
  11. Java反编译工具使用对比,最好用的Java反编译工具 --- JD-GUI、XJad
  12. Platform SDK and SB2
  13. 三方集成 - 友盟分享总结
  14. 查T结果与Z结果的P值[转载]
  15. 最详细的jsp基础教程
  16. Windows系统封装(四)正式封装和测试。
  17. Python警告控制模块:warnings
  18. 动态规划---多边形游戏
  19. Java基础—数据类型
  20. html浏览器标题闪动,一个网页标题title的闪动提示效果实现思路

热门文章

  1. linux把一个文件拷贝到另一个目录,linux把某个文件拷贝到不同的目录下面
  2. 使用systemd来构建你的服务
  3. 利用jira-python及selenium完成jira的统计报表及日报的填写
  4. CentOS 7.4 安装Nginx
  5. 菜鸟学Linux 第048篇笔记 配置slave server
  6. 编写可靠 shell 脚本的 8 个建议
  7. android之自定义弹框
  8. 5道经典面试题【转载】
  9. ASP.NET文件的上传与下载
  10. [导入]一个Form验证的方案