Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61832

"cannot increment endIndex" - Error because of emoji characters in UITextView

I have extension for UITextView:

extension UITextView {

    func separatedWordsInFrontCursor(infront: Bool = true) -> [String] {

        let cursorPosition = selectedRange.location
        let separationCharacters = NSCharacterSet(charactersInString: " ")

        let beginRange = Range(start: text.startIndex.advancedBy(0), end: text.startIndex.advancedBy(cursorPosition))
        //fatal error: can not increment endIndex

        let endRange = Range(start: text.startIndex.advancedBy(cursorPosition), end: text.startIndex.advancedBy(text.characters.count))

        let beginPhrase = text.substringWithRange(beginRange)
        let endPhrase = text.substringWithRange(endRange)

        return infront ? beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters) : endPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
    }
}

Error is following:

fatal error: can not increment endIndex

This is what I try to type into UITextView:enter image description here

Keyboard type for UITextView is set to Default.

When error arise:

cursorPosition is 3
text.characters.count is 2
text.startIndex is 0
text.startIndex.advancedBy(2) is 3
text.startIndex.advancedBy(cursorPosition) is "fatal error: can not increment endIndex"

How can I workaround this?

Upvotes: 4

Views: 666

Answers (1)

Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61832

As @Martin R said we need to operate on NSRange and NSString, so the solution is following:

private func separatedWordsInFrontCursor(infront: Bool = true) -> [String] {

    let cursorPosition = selectedRange.location
    let separationCharacters = NSCharacterSet(charactersInString: " ")

    let nstext = NSString(string: text)

    let beginRange = NSRange(location: 0, length: cursorPosition)
    let endRange = NSRange(location: cursorPosition, length: nstext.length - cursorPosition)

    let beginPhrase = nstext.substringWithRange(beginRange)
    let endPhrase = nstext.substringWithRange(endRange)

    return infront ? beginPhrase.componentsSeparatedByCharactersInSet(separationCharacters) : endPhrase.componentsSeparatedByCharactersInSet(separationCharacters)
}

Upvotes: 1

Related Questions