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.swift200 chars5 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