Search code examples
nsstringswiftios8nsrange

NSRange to Range<String.Index>


How can I convert NSRange to Range<String.Index> in Swift?

I want to use the following UITextFieldDelegate method:

    func textField(textField: UITextField!,
        shouldChangeCharactersInRange range: NSRange,
        replacementString string: String!) -> Bool {

textField.text.stringByReplacingCharactersInRange(???, withString: string)

enter image description here


Solution

  • The NSString version (as opposed to Swift String) of replacingCharacters(in: NSRange, with: NSString) accepts an NSRange, so one simple solution is to convert String to NSString first. The delegate and replacement method names are slightly different in Swift 3 and 2, so depending on which Swift you're using:

    Swift 3.0

    func textField(_ textField: UITextField,
                   shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
    
      let nsString = textField.text as NSString?
      let newString = nsString?.replacingCharacters(in: range, with: string)
    }
    

    Swift 2.x

    func textField(textField: UITextField,
                   shouldChangeCharactersInRange range: NSRange,
                   replacementString string: String) -> Bool {
    
        let nsString = textField.text as NSString?
        let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string)
    }