As the title suggests, I'm trying to sort an existing Dictionary of type [Character : Int] based on the value count, with most repeated characters appearing first. The following code returns the error error: cannot convert return expression of type '[(key: Character, value: Int)]' to return type '[Character : Int]
. Now, I get that my function is returning an array of Tuples but I can't understand how...
Here's the code:
let str = "the brown fox jumps over the lazy dog"
func characterCount(str: String) -> [Character : Int] {
var results: [Character : Int] = [:]
for char in str {
results[char] = 0
let charCount = str.filter { char == $0 }
results[char] = charCount.count
}
let sortedResults = results.sorted { $0.value < $1.value }
return sortedResults
}
print(characterCount(str: str))
CodePudding user response:
As Sweeper notes, dictionaries are inherently unordered, so you will need to transform the dictionary into something sortable. The simplest option here is an array of tuples
let sorted = str
.reduce(into: [Character: Int]()){ $0[$1] = $0[($1), default: 0] 1}
.map{($0.key, $0.value)}
.sorted{$0.1 > $1.1}
This answer uses reduce(into:)
to create the dictionary from the string, but you could use a for loop if you prefer. It then maps the dictionary into an array of tuples of (Character, Int)
where the Character is the dictionary key (i.e. the string character) and the Int is it's value (i.e. the character's count), and sorts that based on the value of the count.