1

How do I convert this to Swift:

NSString *searchString = [NSString stringWithFormat:@"%@", @"Apple_HFS "];
NSRange range = [tempString rangeOfString:searchString];
NSUInteger *idx = range.location + range.length;

Thanks

Zigii Wong
  • 7,766
  • 8
  • 51
  • 79
jbrown94305
  • 185
  • 2
  • 11

3 Answers3

1

Is that what you're looking for ?

var str : NSString = "A string that include the searched string Apple_HFS inside"

let searchString : NSString = "Apple_HFS "
let range : NSRange = str.rangeOfString(searchString) // (42, 10)
let idx : Int = range.location + range.length // 52

Demonstration : http://swiftstub.com/831969865/

lchamp
  • 6,592
  • 2
  • 19
  • 27
1

If you use String, you can just reference endIndex:

let searchString: String = "Apple_HFS "
if let range: Range<String.Index> = tempString.rangeOfString(searchString) {
    let index = range.endIndex
    let stringAfter = tempString.substringFromIndex(index)
    // do something with `stringAfter`
} else {
    // not found
}

I included the types so you could see what's going on, but generally I'd just write:

let searchString = "Apple_HFS "
if let range = tempString.rangeOfString(searchString) {
    let stringAfter = tempString.substringFromIndex(range.endIndex)
    // do something with `stringAfter`
} else {
    // not found
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

Simple solution without using ANY objc methods or types:

Suppose you have:

let nsrange = NSRange(location: 3, length: 5)
let string = "My string"

And now you need to convert NSRange to Range:

let range = Range(start: advance(string.startIndex, nsrange.location), end: advance(string.startIndex, nsrange.location + nsrange.length))
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Don't use this code. It will not work with composed characters or emojis. Ranges in Objective-C represent UTF-16 code units. Ranges in Swift represent extended grapheme clusters. If you don't understand what I am talking about, read the Swift documentation about Strings. – Jakob Egger Dec 09 '15 at 10:29