我的主力博客:半亩方塘

Dictionaries


1、A dictionary is an unordered collection of pairs, where each pair is comprised of a keyand a value. The same key can’t appear twice in a dictionary, but different keys may point to the same value. All keys have to be of the same type, and all values have to be of the same type.

2、When you create a dictionary, you can explicitly declare the type of the keys and the type of the values:

let pairs: Dictionary<String, Int>

Swift can also infer the type of a dictionary from the type of the initializer:

let inferredPairs = Dictionary<String, Int>()

Or written with the preferred shorthand:

let alsoInferredPairs = [String: Int]()

Within the square brackets, the type of the keys is followed by a colon and the type of the values. This is the most common way to declare a dictionary.

If you want to declare a dictionary with initial values, you can use a dictionary literal. This is a list of  key-value pairs separated by commas, enclosed in square brackets:

let namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
print(namesAndScores)
// > ["Brian": 2, "Anna": 2, "Craig": 8, "Donna": 6]

In this example, the dictionary has pairs of [String: Int]. When you print the dictionary, you see there’s no particular order to the pairs.

An empty dictionary literal looks like this: [:]. You can use that to empty an existing dictionary like so:

var emptyDictionary: [Int: Int]
emptyDictionary = [:]

3、Dictionaries support subscripting to access values. Unlike arrays, you don’t access a value by its index but rather by its key. For example, if you want to get Anna’s score, you would type:

print(namesAndScores["Anna"])
// > Optional(2)

Notice that the return type is an optional. The dictionary will check if there’s a pair with the key “Anna”, and if there is, return its value. If the dictionary doesn’t find the key, it will return  nil:  

print(namesAndScores["Greg"])
// > nil

Properties and methods:

print(namesAndScores.isEmpty)
// > false
print(namesAndScores.count)
// > 4print(Array(namesAndScores.keys))
// > ["Brian", "Anna", "Craig", "Donna"]
print(Array(namesAndScores.values))
// > [2, 2, 8, 6]

4、Take a look at Bob’s info:

var bobData = ["name": "Bob", "profession": "Card Player", "country": "USA"]

Let’s say you got more information about Bob and you wanted to add it to the dictionary. This is how you’d do it:

bobData.updateValue("CA", forKey: "state")

There’s even a shorter way, using subscripting:

bobData["city"] = "San Francisco"

You want to change Bob’s name from Bob to Bobby:

bobData.updateValue("Bobby", forKey: "name"]
// > Bob

Why does it return the string “Bob”? updateValue(_:forKey:) replaces the value of the given key with the new value and returns the old value. If the key doesn’t exist, this method will add a new pair and return nil.

As with adding, you can change his profession with less code by using subscripting:

bobData["profession"] = "Mailman"

Like the first method, the code updates the value for this key or, if the key doesn’t exist, creates a new pair.

You want to remove all information about his whereabouts:

bobData.removeValueForKey("state")

As you might expect, there’s a shorter way to do this using subscripting:

bobData["city"] = nil

Assigning nil as a key’s associated value removes the pair from the dictionary.

5、The for-in loop also works when you want to iterate over a dictionary. But since the items in a dictionary are pairs, you need to use tuple:

for (key, value) in namesAndScores {print("\(key) - \(value)")
}
// > Brian - 2
// > Anna - 2
// > Craig - 8
// > Donna - 6

It’s also possible to iterate over just the keys:

for key in namesAndScores.keys {print("\(key),", terminator: "")  // no newline
}
print("") // print one final newline
// > Brian, Anna, Craig, Donna,

You can iterate over just the values in the same manner with the values property on the dictionary.

6、You could use reduce(_:combine:) to replace the previous code snippet with a single line of code:

let namesString = namesAndScores.reduce("", combine: { $0 + "\($1.0)," })
print(namesString)

In a reduce statement, $0 refers to the partially-combined result, and $1 refers to the current element. Since the elements in a dictionary are tuples, you need to use $1.0 to get the key of the pair.

Let’s see how you could use filter(_:) to find all the players with a score of less than 5:

print(namesAndScores.filter({ $0.1 < 5 }))
// > [("Brian", 2), ("Anna", 2)]

Here you use $0.1 to access the value of the pair.

Swift 笔记(十)相关推荐

  1. swift 笔记 (十二) —— 下标

    下标 swift同意我们为 类.结构体,枚举 定义下标,以更便捷的方式訪问一大堆属性.比方Array和Dictionary都是结构体,swift的project师已经为这两个类型提供好了下标操作的代码 ...

  2. swift 笔记 (十四) —— 构造过程

    构造过程 为了生成类.结构体.枚举等的实例,而做的准备过程,叫做构造过程. 为了这个过程,我们一般会定义一个方法来完毕,这种方法叫做构造器.当然它的逆过程,叫做析构器,用于在实例被释放前做一些清理工作 ...

  3. 机器学习笔记十四:随机森林

    在上一篇机器学习笔记十三:Ensemble思想(上)中,简要的提了一下集成学习的原理和两种主要的集成学习形式.  而在这部分要讲的随机森林,就算是其中属于bagging思路的一种学习方法.为了篇幅,b ...

  4. python中计算排队等待时间_codewars(python)练习笔记十:计算超市排队时长

    codewars(python)练习笔记十:计算超市排队时长 题目 There is a queue for the self-checkout tills at the supermarket. Y ...

  5. IOS之学习笔记十五(协议和委托的使用)

    1.协议和委托的使用 1).协议可以看下我的这篇博客 IOS之学习笔记十四(协议的定义和实现) https://blog.csdn.net/u011068702/article/details/809 ...

  6. 吴恩达《机器学习》学习笔记十四——应用机器学习的建议实现一个机器学习模型的改进

    吴恩达<机器学习>学习笔记十四--应用机器学习的建议实现一个机器学习模型的改进 一.任务介绍 二.代码实现 1.准备数据 2.代价函数 3.梯度计算 4.带有正则化的代价函数和梯度计算 5 ...

  7. 吴恩达《机器学习》学习笔记十二——机器学习系统

    吴恩达<机器学习>学习笔记十二--机器学习系统 一.设计机器学习系统的思想 1.快速实现+绘制学习曲线--寻找重点优化的方向 2.误差分析 3.数值估计 二.偏斜类问题(类别不均衡) 三. ...

  8. 吴恩达《机器学习》学习笔记十——神经网络相关(2)

    吴恩达<机器学习>学习笔记十--神经网络相关(2) 一. 代价函数 二. 反向传播算法 三. 理解反向传播算法 四. 梯度检测 五. 随机初始化 1.全部初始化为0的问题 2.随机初始化的 ...

  9. 主成分分析碎石图_ISLR读书笔记十九:主成分分析(PCA)

    本文使用 Zhihu On VSCode 创作并发布 前面写的一些统计学习方法都是属于监督学习(supervised learning),这篇主成分分析(principal components an ...

  10. Mr.J-- jQuery学习笔记(十九)--自定义动画实现图标特效

    之前有写过自定义动画Mr.J-- jQuery学习笔记(十八)--自定义动画 这次实现一个小demo 图标特效 页面渲染 <!DOCTYPE html> <html lang=&qu ...

最新文章

  1. Joiner的简单了解
  2. 探究C/C++可变参数
  3. 大学计算机基础课程报告python-Python程序设计习题解析(大学计算机基础教育规划教材)...
  4. python3教程-终于清楚python3详细教程
  5. React + TypeScript:元素引用的传递
  6. MyBatis 插件原理与自定义插件-用代理模式我们就要解决几个问题
  7. 备忘录——通过RVA计算文件位置
  8. 【转】GigE Vision简介
  9. linux启动过程剖析,分析Linux系统的启动过程
  10. 2016年的云计算安全趋势
  11. 无限级分类 php_php无限极分类的方法是什么
  12. Ubuntu9.04更新源
  13. Linux下解决MySQL无法远程连接问题(转)
  14. jvisualVm用法
  15. 个人总结 超详细 windows10下载与安装
  16. Java开源电商系统
  17. MyBatis下载和环境搭建
  18. Jlink 接口定义
  19. 第一范式、第二范式、第三范式、BCNF范式通俗理解
  20. 2020年中国水利行业发展状况及未来发展趋势分析[图]

热门文章

  1. 重磅资讯:《数据安全法》颁布,国家支持数据开发利用和数据安全技术研究
  2. WordPress正确使用51la统计来统计网站访问数据[WP教程]
  3. matlab怎么产生帕斯卡矩阵,MATLAB(一):矩阵基本操作
  4. [brew|Mac]如何将软件发布到Homebrew
  5. 怎样把ogg格式转换mp3
  6. 路由器重温——WAN接入/互联-DCC配置管理1
  7. 物联网智能家居需要服务器吗,智能家居设备常见的两种配网/联网方式
  8. C语言实验系统PPT展示,c语言第四谭浩强机实验课件.ppt
  9. java.lang.NoSuchMethodError: net.sf.jsqlparser.statement.update.Update.getTable()Lnet/sf/jsqlparser/
  10. InternalError: Dst tensor is not initialized. 的产生原因和解决办法