Range(nsRange, in: string) to convert an NSRange to a Rangetext.replacingCharacters(in: Range(range, in: text)!, with: string) to compute the new text after a change.Why this happens
UIKit APIs like UITextFieldDelegate report text ranges as NSRange, which measures offsets in UTF-16 code units. Swift’s native String uses String.Index based on extended grapheme clusters, so the two range types are not directly interchangeable. Passing an NSRange to a Swift String method causes a type mismatch, and manually calculating indices can break with emoji, flags, or other multi-code-unit characters.
Before Swift 4, developers had to bridge through NSString or write custom UTF-16 offset conversions. Since Swift 4 (Xcode 9), the standard library provides safe, Unicode-correct initializers for both directions.
How to fix it
1. Use the standard library initializer (Swift 4+)
The simplest and safest approach is the Range(_:in:) initializer added in Swift 4. It takes an NSRange and the source String, returning an optional Range<String.Index> that is nil when the range is invalid for that string.
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let currentText = textField.text,
let swiftRange = Range(range, in: currentText) else { return true }
let newText = currentText.replacingCharacters(in: swiftRange, with: string)
// Validate newText, update model, etc.
return true
}
Why this works: The initializer handles all Unicode edge cases—emoji, regional indicators, combining marks—because it operates on the string’s actual UTF-16 view internally.
2. Bridge through NSString (legacy Swift 2/3)
If you maintain older codebases, casting to NSString lets you call replacingCharacters(in:with:) directly with the NSRange.
// Swift 3
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)
// ...
return true
}
// Swift 2
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
let nsString = textField.text as NSString?
let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string)
// ...
return true
}
Trade-off: This works but adds an NSString bridge hop and loses Swift’s native String semantics.
3. Manual UTF-16 conversion (Swift 1.2–3, not recommended)
Early Swift versions exposed String.Index(utf16Index:within:) for manual conversion. It is verbose, error-prone, and unnecessary today.
extension String {
func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) else { return nil }
return from..<to
}
}
Avoid this in modern code; the standard library initializer is tested and maintained by Apple.
How to prevent it
- Always use
Range(nsRange, in: string)for new code targeting Swift 4 or later. - Guard the optional result; an invalid
NSRange(e.g., from a corrupted delegate call) returnsnilinstead of crashing. - Prefer Swift
Stringmethods (replacingCharacters(in:with:)) overNSStringbridging to keep Unicode handling consistent. - When exposing ranges to Objective-C, convert back with
NSRange(swiftRange, in: string).
FAQ
Does Range(nsRange, in: string) handle emoji and flags correctly?
Yes. The initializer accounts for extended grapheme clusters, so characters like “👨👩👧👦” or “🇩🇪” are treated as single positions.
What happens if the NSRange is out of bounds?
The initializer returns nil. Always unwrap safely with guard let or if let before using the range.
Can I convert back from Range<String.Index> to NSRange?
Yes. Use NSRange(swiftRange, in: string) when you need to pass a range to UIKit or Objective-C APIs.{
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.