Effectively remove the last word from a string in Swift

I’m trying to create an automatic correction system, so I need to delete the last word entered and replace it with the correct one. My decision:

func autocorrect() { hasWordReadyToCorrect = false var wordProxy = self.textDocumentProxy as UITextDocumentProxy var stringOfWords = wordProxy.documentContextBeforeInput fullString = "Unset Value" if stringOfWords != nil { var words = stringOfWords.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) for word in words { arrayOfWords += [word] } println("The last word of the array is \(arrayOfWords.last)") for (mistake, word) in autocorrectList { println("The mistake is \(mistake)") if mistake == arrayOfWords.last { fullString = word hasWordReadyToCorrect = true } } println("The corrected String is \(fullString)") } } 

This method is called after each keystroke, and if space is pressed, it corrects the word. My problem arises when a line of text becomes longer than 20 words. This takes some time to fill the array every time a symbol is clicked, and it begins to lag behind the fact that it cannot use it. Is there a more efficient and elegant way to quickly record this feature? I would be grateful for any help!

+6
source share
2 answers

1.

One thing, iteration is not needed for this:

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

You can simply do:

 arrayOfWords += words 

2.

Aborting the for loop will prevent unnecessary repetition:

 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 completely for the loop:

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

Ultimately, what you do is see if the last word of the entered text matches any of the keys in the AutoCorrect list. You can simply try to get the value directly using an optional binding like this.

---

I will let you know if I think more.

+5
source

This does not answer the OP autosave problem directly, but this code is probably the easiest way to answer the question asked in the header :

Swift 3

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

Source: https://habr.com/ru/post/976449/


All Articles