0

I have the following function to return sorted dictionary but I'm getting this error:

Cannot convert value of type [(key:string,value:int)] to specified type Dictionary<String,Int>

Here is my code:

func generatDictionaryFromString(str:String) -> Dictionary<String,Int>{
    var charDict = Dictionary<String,Int>()
    /* doing something here
     */
    return charDict.sorted(by:<) // <-- line with the error
}

Does anyone know why I'm getting this error?

Hamish
  • 78,605
  • 19
  • 187
  • 280
user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

4

It is Swift Type Error

Swift type of result is [(key: String, value: Int)] and function return type is Dictionary so it report error

So, It is solved by

Option :1) changing return type of function

func generatDictionaryFromString(str:String) -> [(key: String, value: Int)]{
    let charDict = Dictionary<String,Int>()
    /* doing something here
     */
    return charDict.sorted(by:<)    
}

Option :2) Changing return value.

func generatDictionaryFromString(str:String) -> (key: String, value: Int)? {
    let charDict = Dictionary<String,Int>()
    /* doing something here
     */
    return charDict.sorted(by:<).first   
}

As per your requirement you can change your implementation.

ERbittuu
  • 968
  • 8
  • 19
1

You can't sort a dictionary. Dictionaries don't have an order, therefore they cannot have a sorted order.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • 2
    @user2924482 you can sort a dictionary but the result will always be an array of key/value pairs (tuple) – Leo Dabus Feb 10 '17 at 19:50