swift 字典 添加元素
This article is originally published at https://swiftsenpai.com on June 30, 2020.
本文最初于 2020年6月30日 发布在 https://swiftsenpai.com 上。
Imagine you have an array of Device
objects and you want to group them by category as shown in the image below:
假设您有一个Device
对象数组,并且想要按类别对它们进行分组,如下图所示:
How should you go about in solving this problem?
您应该如何解决这个问题?
Before Swift 5, the most straightforward way is to loop through each device in the array and manually assign each element to its respective category. In Swift 5, Apple has introduced a generic dictionary initializer to help developers deal with this kind of situation with just 1 single line of code.
在Swift 5之前,最直接的方法是遍历数组中的每个设备,并将每个元素手动分配给其各自的类别。 在Swift 5中,Apple引入了一个通用的字典初始化程序,以帮助开发人员仅用一行代码即可处理这种情况。
Wondering how this can be done? Read on to find out more.
想知道如何做到这一点? 请继续阅读以了解更多信息。