func buildIndex(words: [String]) -> [Entry] {
var result = [Entry]()
var letters = [Character]()
for word in words {
let firstLetter = Character(word.substringToIndex(word.startIndex.advancedBy(1)).uppercaseString)
if !letters.contains(firstLetter) {
letters.append(firstLetter)
}
}
for letter in letters {
var wordsForLetter = [String]()
for word in words {
let firstLetter = Character(word.substringToIndex(word.startIndex.advancedBy(1)).uppercaseString)
if firstLetter == letter {
wordsForLetter.append(word)
}
}
result.append((letter, wordsForLetter))
}
return result
}
Colin, Thank you for the tutorial. I am a big fan of functional programming. Ocaml was my language of choice in the past. Itβs been over 10 years since I have even thought about it. Your tutorial reintroduced it to me for Swift.
Itβs a fun and thought provoking style of programming.
Hereβs the build using the Swiftz library found on GitHub.
The extension to the string is simply for readability in the final function
process: reverse the array, process the words into a Dictionary of type [Character:[String], convert the dictionary into [Entry], then sort it based on the first in the tuple.
I reverse the array so that the results match the order of the original imperative style. This is covering the difference between appending to an array and consβing an array.
Thanks a lot for this great article. I was learning this with Swift 4.
The functions as modified for Swift 4.0 (function distinct generic changed to Comparable from Equatable and return collection sorted for the last challenge):
func distinct<T: Comparable>(_ source: [T]) -> [T] {
var unique = [T]()
for item in source {
if !unique.contains(item) {
unique.append(item)
}
}
return unique.sorted(by: <)
}
func buildIndex(words: [String]) -> [Entry] {
func firstLetter(_ str: String) -> Character {
return Character((str as NSString).substring(to: 1).uppercased())
}
return distinct(words.map(firstLetter)).map { (letter) -> Entry in
return (letter, words.filter { (word) -> Bool in
firstLetter(word) == letter
})
}
}
This tutorial is more than six months old, so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]