ios - 从键值对数组创建键数组

标签 ios arrays swift keyvaluepair

最初,我对一个返回键值对数组的字典进行了排序,并试图将其转换为字典,当我被告知字典的顺序是随机的,因此我所做的事情是无用的。我试图将这个键值对数组转换为仅包含键的数组,并且想知道如何做到这一点。这是我的代码:

    let posts = ["post1" : 3, "post2" : 41, "post3" : 27]

    let sortedPS = posts.sorted { $1.1 < $0.1 }

posts是一本字典并且 sortedPS类型为Array<(key: String, value: Int)>据我所知,是一个键值对数组/元组数组。 sortedPS应该是一个元组数组,如下所示:

    ["post2" : 41, "post3" : 27, "post1" : 3]

我想要一个数组,它应该如下所示:

    ["post2", "post3", "post1"]

请告诉我如何从 sortedPS 获取 key 并生成一个数组。

最佳答案

您可以使用下面的短代码从字典中获取所有键。

let posts = ["post1" : 3, "post2" : 41, "post3" : 27]

let sortedPS = posts.sorted { $1.1 < $0.1 }

let keys = sortedPS.map { $0.key } // ["post2", "post3", "post1"]

关于ios - 从键值对数组创建键数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51514118/

相关文章:

ios - Xcode - 无法编译添加的框架

swift - NSRegularExpressions - 非捕获组不工作

ios - 如何在标签行数下调整 UIView 的大小?

ios - 谷歌驱动器选项在 IOS10 的 UIDocumentMenuViewController 中不可见

ios - Swift:从后台重新打开应用程序,willEnterForeground 在 appdelegate 之前运行

ios - iOS-脏内存持续增长

swift - 实现 AVCaptureFileOutputDelegate 和 AVCaptureVideoDataOutputSampleBufferDelegate

javascript - 如何分配多维数组中的单个元素 (JavaScript)

jquery - 带有嵌套对象的 json 对象

ruby - 数组数组中的唯一元素