Swift
NSRange
Swift Range
iOS Development
Programming

NSRange from Swift Range?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Swift strings use Range<String.Index> while many Foundation and Objective-C APIs use NSRange. Converting between them is common in iOS development, but the conversion must always be tied to the specific string involved.

The safe rule is simple: let Foundation do the conversion for you. Manual integer math is fragile because Swift strings are Unicode-aware and do not map cleanly to visible-character counts.

If you stay on the official conversion APIs, most of the tricky Unicode edge cases disappear from your application code.

Convert a Swift Range to NSRange

If you already have a native Swift range, convert it like this:

swift
1import Foundation
2
3let text = "Hello, world"
4let swiftRange = text.range(of: "world")!
5let nsRange = NSRange(swiftRange, in: text)
6
7print(nsRange.location)
8print(nsRange.length)

That initializer understands the string's UTF-16 representation, which is what Foundation APIs expect.

Convert NSRange Back to a Swift Range

When a Foundation API gives you an NSRange, convert it back with the failable Range initializer:

swift
1import Foundation
2
3let text = "Hello, world"
4let nsRange = NSRange(location: 7, length: 5)
5
6if let swiftRange = Range(nsRange, in: text) {
7    let word = text[swiftRange]
8    print(word)
9}

The initializer can fail because not every NSRange is valid for every Swift string. That is a feature, not a nuisance.

Why Manual Offsets Are Dangerous

Swift strings are collections of extended grapheme clusters. Foundation ranges are usually expressed in UTF-16 code units. Those are not always the same thing.

For example:

swift
1import Foundation
2
3let text = "Café"
4print(text.count)
5print((text as NSString).length)

Those numbers can differ. If you build an NSRange from String.count, it may be wrong for emoji, accented characters, or composed Unicode sequences.

Use the Right Range Type for the Right API

Stay in native Swift ranges as long as you are slicing or searching Swift strings. Convert only when an Objective-C or Foundation API requires NSRange.

NSRegularExpression is a common example:

swift
1import Foundation
2
3let text = "Order #12345"
4let regex = try! NSRegularExpression(pattern: "#\\d+")
5
6let match = regex.firstMatch(
7    in: text,
8    range: NSRange(text.startIndex..., in: text)
9)
10
11if let match,
12   let swiftRange = Range(match.range, in: text) {
13    print(text[swiftRange])
14}

This pattern is safe and common: create the full-string NSRange, call the Foundation API, then convert the returned range back into Swift form.

That keeps the Foundation boundary narrow and lets the rest of your code stay in native Swift string types.

Remember That the String Matters

An NSRange is not meaningful by itself. It only means something relative to the exact string it was created from. If the string changes, the range may no longer point to the same text or may become invalid.

That means you should not cache an NSRange and reuse it after editing the underlying string. Recompute the range from the current text instead.

Common Pitfalls

  • Building an NSRange manually from integer counts.
  • Assuming String.count and NSString.length measure the same thing.
  • Forgetting that Range(nsRange, in: string) can fail.
  • Reusing an NSRange after the source string has changed.
  • Staying in NSRange longer than necessary instead of converting back to a Swift range for Swift string work.

Summary

  • Use NSRange(swiftRange, in: string) to convert from Swift range to NSRange.
  • Use Range(nsRange, in: string) to convert back safely.
  • Avoid manual offset math because Swift strings are Unicode-aware.
  • Keep NSRange at Foundation boundaries and prefer Swift ranges elsewhere.
  • Treat every range as valid only for the specific string it came from.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.