Swift version: 5.10
Paul Hudson
Swift strings have changed in every release since the language was first announced, but even after so much change its older counterpart,
NSRange
, still appears in many UIKit APIs.
Fortunately, Swift 4 introduced a simple way to convert any
NSRange
into a regular Swift
Range
. For example, say you had the following string and range:
let input = "Hello, world"
let range = NSMakeRange(0, 10)
To make that into a Swift
Range
instance you just need this single line of code:
let swiftRange = Range(range, in: input)
SPONSORED
Join some of the App Store’s biggest apps—from brands like Mojo and Citizen to thriving indies. Test pricing, run paywall experiments, update locked features, and now, launch web checkout links straight from your app—all without updates. Superwall is your complete growth toolkit.
Try now
Available from iOS 7.0
Similar solutions…
About the Swift Knowledge Base
This is part of the
Swift Knowledge Base
, a free, searchable collection of solutions for common iOS questions.
Swift, SwiftUI, the Swift logo, Swift Playgrounds, Xcode, Instruments, Cocoa Touch, Touch ID, AirDrop, iBeacon, iPhone, iPad, Safari, App Store, watchOS, tvOS, visionOS, Mac and macOS are trademarks of Apple Inc., registered in the U.S. and other countries. Pulp Fiction is copyright © 1994 Miramax Films.
Hacking with Swift is ©2025
Hudson Heavy Industries
.