Skip to content

Instantly share code, notes, and snippets.

@ilyarmnzhdn
Created November 1, 2017 09:28
Show Gist options
  • Save ilyarmnzhdn/aa67838f392c532ede16861dfed93c42 to your computer and use it in GitHub Desktop.
Save ilyarmnzhdn/aa67838f392c532ede16861dfed93c42 to your computer and use it in GitHub Desktop.
Find the longest word in string (Swift 4)
func findLongestWord(word: String) -> String {
let wordArray = word.components(separatedBy: " ")
var maxLength = 0
for index in 0..<(wordArray.count) {
if wordArray[index].count > maxLength {
maxLength = wordArray[index].count
}
}
return "\(maxLength)"
}
findLongestWord(word: "The quick brown fox jumped over the lazy dog")
@mastermind247
Copy link

mastermind247 commented May 22, 2018

Optimized code:

func findLongestWord(word: String) -> String? {
    if let longestWord = word.components(separatedBy: " ").max(by: { $1.count > $0.count }) {
        return longestWord
    }
    
    return nil
}

let longestWord = findLongestWord(word: "The quick brown fox jumped over the lazy dog")
print(longestWord?.count)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment