import Foundation
func secondLargestWord(in str: String) -> String? {
let words = str.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let sortedWords = words.sorted { $0.count > $1.count }
guard sortedWords.count > 1 else {
return nil
}
return sortedWords[1]
}
let str = "Swift is a powerful programming language for iOS, iPadOS, macOS"
if let secondLargest = secondLargestWord(in: str) {
print("The second largest word is: \(secondLargest)")
} else {
print("There are not enough words in the string.")
}
/*
run:
The second largest word is: powerful
*/