首页 文章

从键值对数组创建键数组

提问于
浏览
0

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

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 获取密钥并生成一个数组 .

2 回答

  • 0

    您可以使用以下短代码从字典中获取所有密钥 .

    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"]
    
  • 0

    Short way:

    print(Array(posts.keys))
    print(Array(posts.values))
    Result:
    ["post2", "post3", "post1"]
    

相关问题