import Foundation
func replaceRandomWord(_ text: String, with replacements: [String]) -> String {
var words = text.split(separator: " ").map(String.init)
guard !words.isEmpty, !replacements.isEmpty else {
return text // nothing to do
}
// Pick random index in the sentence
let idx = Int.random(in: 0..<words.count)
// Pick random replacement word
if let newWord = replacements.randomElement() {
words[idx] = newWord
}
// Rebuild the string
return words.joined(separator: " ")
}
let text = "The quick brown fox jumps over the lazy dog"
let replacementWords = ["c#", "c++", "java", "rust", "python"]
let result = replaceRandomWord(text, with: replacementWords)
print(result)
/*
run:
The quick brown fox jumps over c++ lazy dog
*/