Reputation: 185
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
Upvotes: 1
Views: 2600
Reputation: 61784
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))
Upvotes: 0
Reputation: 437632
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
}
Upvotes: 1
Reputation: 6612
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/
Upvotes: 1