find the longest word in a string in swift

One way to find the longest word in a string in Swift is to split the string into an array of words and then use the reduce method to find the longest word. Here's the code:

main.swift
let str = "The quick brown fox jumps over the lazy dog"
let words = str.components(separatedBy: " ")
let longestWord = words.reduce("") { $1.count > $0.count ? $1 : $0 }
print(longestWord) // "jumps"
200 chars
5 lines

First, we split the string into an array of words using the components(separatedBy:) method on the string with a space as the separator. Then, we call reduce on the array of words, initializing the accumulator ($0) to an empty string and the current value ($1) to the first word in the array. Then, for each subsequent word in the array, we check if its length is greater than the length of the current longest word and if so, we replace the current longest word with the new word. Finally, we print out the longest word found.

gistlibby LogSnag