Efficiently remove the last word from a string in Swift

This doesn't answer the OP's "autocorrect" issue directly, but this is code is probably the easiest way to answer the question posed in the title:

Swift 3

let myString = "The dog jumped over a fence"
let myStringWithoutLastWord = myString.components(separatedBy: " ").dropLast().joined(separator: " ")

1.

One thing, iteration isn't necessary for this:

for word in words {
    arrayOfWords += [word]
}

You can just do:

arrayOfWords += words

2.

Breaking the for loop will prevent iterating unnecessarily:

for (mistake, word) in autocorrectList {
    println("The mistake is \(mistake)")
    if mistake == arrayOfWords.last {
        fullString = word
        hasWordReadyToCorrect = true
        break; // Add this to stop iterating through 'autocorrectList'
    }
}

Or even better, forget the for-loop completely:

if let word = autocorrectList[arrayOfWords.last] {
    fullString = word
    hasWordReadyToCorrect = true
}

Ultimately what you're doing is seeing if the last word of the entered text matches any of the keys in the autocorrect list. You can just try to get the value directly using optional binding like this.

---

I'll let you know if I think of more.

Tags:

String

Swift