Tel Tel - 4 months ago 45
Swift Question

How to select a text in a textView having a NSRange in Swift?

I have a

where I would like to select a part of the text. I'm trying to use
, unfortunately I get this error:

Cannot convert value of type 'NSRange' (aka '_NSRange') to expected
argument type 'UITextRange'

This is the code I'm trying to use:

mainTextField.selectedTextRange = mainTextField.textInRange(matchRange)

The range I'm using is coming from a Regex which I adapted from this tutorial1:

EDIT: added the first line

if let regex = NSRegularExpression(options: searchOptions){
let range = NSMakeRange(0, (mainTextField.text.characters.count))
let matches = regex.matchesInString(mainTextField.text, options: [], range: range)


You can add an extension on UITextView that will do the conversion.

    extension UITextView
        func textRangeFromNSRange(range:NSRange) -> UITextRange?
            let beginning = self.beginningOfDocument
            guard let start = self.positionFromPosition(beginning, offset: range.location), end = self.positionFromPosition(start, offset: range.length) else { return nil}

            return self.textRangeFromPosition(start, toPosition: end)


    if let range = mainTextView.textRangeFromNSRange(range: matchRange){
        mainTextField.selectedTextRange = range

Where matchRange is an NSRange and range is a UITextRange