"NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds"

Hi guys, I'm new to swift! I would like to add a link to a text inside my View Controller, I found this code below.

When I run the App crash and is returning this error message:

"NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds"

I appreciate any help, thanks.

class ViewController: UIViewController, UITextViewDelegate { @IBOutlet var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    let attributedString = NSMutableAttributedString(string: "Link")
    attributedString.addAttribute(.link, value: "https://www.apple.com", range: NSRange(location: 19, length: 55))
    
    textView.attributedText = attributedString
}
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    UIApplication.shared.open(URL)
    return false
}

}

Answered by robnotyou in 713344022

Your attributedString is "Link"
You are referencing location 19, length 55 of attributedString...

...isn't that way beyond the end of attributedString?

I suggest you check the documentation for addAttribute(_:value:range:)

Apple say:

Raises... rangeException if any part of aRange lies beyond the end of the receiver’s characters.

Accepted Answer

Your attributedString is "Link"
You are referencing location 19, length 55 of attributedString...

...isn't that way beyond the end of attributedString?

I suggest you check the documentation for addAttribute(_:value:range:)

Apple say:

Raises... rangeException if any part of aRange lies beyond the end of the receiver’s characters.

"NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds"
 
 
Q