I have been trying to learn the various aspects of the languages I know so far to do the Daily Challenges in reddit (/r/DailyProgrammer). The one which I am working on just now asks for an alphabetised count of the occurrences of letters in a string e.g: "Hello World" -> "d:1 e:1 h:1 l:3 o:2 r:1 w:1".
I have tried to write this seemingly simple challenge in Swift (I had already done it in C#, JavaScript and F#), but after longer than should have been the case, I have arrived at the following solution which seems a bit messy to me:
func countLetters(input: String) -> String {
// Convert to Lowercase
var lower = input.lowercaseString
// Filter out invalid characters ([a-z] only)
var validCharacters = filter(lower) { $0 >= Character("a") && $0 <= Character("z") }
// Create a dictionary to build the letter counts
var letterCounts = Dictionary<Character, Int32>()
// Go through the characters and add to the dictionary
for i in validCharacters {
if letterCounts[i] != nil { // If already exists, add one to the count
letterCounts[i] = letterCounts[i]! + 1
} else {
letterCounts[i] = 1 // If doesn't exist, add to the dictionary with a count of 1
}
}
// Unfortunately the Dictionary does not seem to be sorted / sortable, so we need to
// create an Array of the stringified version to allow sorting
var stringifiedCounts = Array<String>()
// Convert each dictionary item to a 'a:1' type string
for (k,v) in letterCounts {
stringifiedCounts.append("\(k):\(v) ")
}
// Sort the list
sort(&stringifiedCounts)
// Concatenate the results
var output = ""
for i in stringifiedCounts {
output += i
}
// Remove the last space
return output.substringToIndex(advance(output.startIndex, countElements(output) - 1))
}
I was going to ask the question in my reply on Reddit, but I am quite late with it, so I doubt anyone will be looking.
For those who have been more regularly using Swift, is there a cleaner way to deal with Dictionaries so that I don't have to covert it to an array before sorting? What are some of the cleverer ways to get the same results?