Trying to make function that makes a valid word out of a word


I am a total Swift beginner, so I apologize if my question is silly. I was trying to write a function that would make a valid English word out of another word.

I'll post the code I have written so far here... it doesn't work at all, but I am hoping to get any feedback anyone is willing to provide. If you can also point me towards some references that might help me figure out how to do this that would be amazing.

func validWord(in word: String) -> String {
    let letterArray = Array(word.lowercased().trimmingCharacters(in: .whitespacesAndNewlines))
    var newWord = ""
    let checker = UITextChecker()
    let range = NSRange(location: 0, length: newWord.utf16.count)
    let misspelledRange = checker.rangeOfMisspelledWord(in: newWord, range: range, startingAt: 0, wrap: false, language: "en")
    var counter = 0

    while misspelledRange.location == NSNotFound {
        var extraArray = letterArray

        while newWord.count <= letterArray.count {
            let randInt = Int.random(in: 0 ..< extraArray.count)

            extraArray.remove(at: randInt)
            if extraArray.count == 1 {
        counter += 1
        if counter == 1000 {
    return newWord

Note that I have the counter because my first while loop appears to be an infinite one so I just threw it in there to stop things.

Thanks everyone.

The reason you're looping infinitely is that your condition (misspelledRange.location == NSNotFound) never changes, since you only compute misspelledRange once. It looks like you should re-compute it (by calling checker.rangeOfMisspelledWord) after the inner while loop ends.

Also, shouldn't the condition be non-equal (misspelledRange.location != NSNotFound)? You want to loop until the new word is valid — that is, has no misspellings — right?

The larger question is whether it is computationally feasible to search for valid words this way. Compute time is going to go up explosively, depending on the number of letters in the word.

1 Like

Thanks so much Quincey. I really appreciate your detailed reply.

In regards to the larger question you posed, I'd say this is definitely not computationally feasible. I'll keep looking for other ways of solving this problem.

Terms of Service

Privacy Policy

Cookie Policy