Swift - Using NSRange with NSString

Introduction

You can create an NSRange instance and use it directly in the stringByReplacingCharactersInRange() method:

Demo

var str2 = "This is a NSString in Objective-C. " as NSString

var range = str2.rangeOfString("Objective-C")
if range.location != NSNotFound {
    print("Index is \(range.location) length is \(range.length)")
    //Index is 22 length is 11
    str2 = str2.stringByReplacingCharactersInRange(
    range, withString: "Swift")
    print(str2)  //This is a NSString in Swift.
}

The following code uses rangeOfString() method from NSString to find the index of the occurrence of a string within a string:

Demo

var path:NSString = "/Users/wei-menglee/Desktop"
//find the index of the last /
range = path.rangeOfString("/",
    options:NSStringCompareOptions.BackwardsSearch)

if range.location != NSNotFound {
    print("Index is \(range.location)")  //18
}

Related Topic