How to find the longest word in a string with Swift

1 Answer

0 votes
func longestWord(_ s: String) -> String? {
    let words = s.split(separator: " ")
    
    return words.max { $0.count < $1.count }.map(String.init)
}

if let result = longestWord("Could you recommend a good restaurant nearby?") {
    print(result)
}



/*
run:

restaurant

*/

 



answered Mar 3 by avibootz
...