-2

I am confused regarding the functionality of NSRange.

What is the function of NSRange in this code?

shouldChangeTextIn range: NSRange
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Amy
  • 109
  • 1
  • 1
  • 5
  • Have you tried Googling this? –  Dec 20 '18 at 14:35
  • It's clearly explained in the [reference documentation](https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield?language=objc) for the method. – rmaddy Dec 20 '18 at 16:10

1 Answers1

1

Foundation is an old pre-Swift framework. It's mostly written in Objective-C and uses its types. NSRange is a C struct heavily used in Objective-C in conjunction with NSString.

NSString is converted to Swift as String and most methods using NSRange has been converted to methods using Range (or other Swift types). However, in some methods the Objective-C type still exists for various compatibility reasons. UITextViewDelegate and UITextFieldDelegate are prime examples.

To properly use NSRange you should convert String to a NSString first, e.g.:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText: String) -> Bool
    let previousText = (textView.text ?? "") as NSString
    let newText = previousText.replacingCharacters(in: range, with: replacementText)

   ...
}

In this method the range describes the range of string that is being changed. Its locations tells you where the new text is being put and its length tells you how much of previous text is being replaced/removed.

For example a NSRange(location: 2, length: 1) with replacementText: "" tells you that the third character is being removed (e.g. when backspace is pressed).

Sulthan
  • 128,090
  • 22
  • 218
  • 270