返回排序后的Swift字典作为参数

时间:2018-08-12 16:17:15

标签: swift dictionary

我有一个要返回排序字典的函数

func sortDictonary()->[Int:String]
{
    let dic:[Int:String] = [ 1:"B", 0:"A", 2:"C" ]
    let sorted = dic.sorted(by: {$0.0 < $1.0} )
    return sorted
}

但是我得到如下错误:

Cannot convert return expression of type '[(key: Int, value: String)]' to return type '[Int : String]'

如何将排序后的项目转换为标准词典

1 个答案:

答案 0 :(得分:1)

  

我想返回排序后的字典

停止想要那个。没有排序字典这样的东西。您正在执行的操作会创建一个成对数组,该对数组按该对中的第一个排序(有效地,这曾经是字典中的键),并且效果很好。

func sortDictonary()->[(Int,String)]
{
    let dic:[Int:String] = [ 1:"B", 0:"A", 2:"C" ]
    let sorted = dic.sorted(by: {$0.0 < $1.0} )
    return sorted
}