Fatal error: String index is out of bounds Swift

1.2k Views Asked by At

I'm trying to get the substring of text typed in UITextView. Here's my code:

let textString = state.textString
    let replacementTextRange = state.replacementRange
    let substringStart = textString.text.index(
          textString.text.startIndex,
          offsetBy: replacementTextRange.charIndex
        )

    let subStringEnd = textString.text.index(
      textString.text.startIndex,
      offsetBy: replacementTextRange.charIndex + replacementTextRange.length
    )

    let currentTextForReplacementRange = substringStart..<subStringEnd//crashing
let currentTextForReplacement = String(textString.text[currentTextForReplacementRange])

It's crashing when i try to add character at the end of textView.But works if i try to add text in the beginning or in the middle of textView. How do i fix this crash:Thread 1: Fatal error: String index is out of bounds

0

There are 0 best solutions below