I am trying the find some alternative to NSRange.location and NSRange.length in Swift.
I have a string for example sip:[email protected]
I am trying to extract name from it. I can do it using componentsSeperatedBy method from String. But I was wondering whether it can be done using range similar to Objective C.
I already have old legacy Objective C code which I am trying to convert to Swift.
// Extract name from sip:[email protected].....
NSString *name = nil;
NSRange rangeForSip;
NSRange rangeFor@;
rangeForSip = [self rangeOfString: @"sip:"];
if (rangeForSip.location == NSNotFound) {
//Look for sips
rangeForSip = [self rangeOfString: @"sips:"];
}
match2 = [self rangeOfString: @"@"];
if ((rangeForSip.location != NSNotFound) && ([email protected] != NSNotFound)) {
name = [self substringWithRange:NSMakeRange(rangeForSip.location + rangeForSip.length, [email protected] - (rangeForSip.location + rangeForSip.length))];
} else if ([email protected] != NSNotFound) {
// Extract name from sip:[email protected].....
name = [self substringWithRange:NSMakeRange(0, [email protected])];
}
Similar to the
rangemethod inNSString, SwiftStringsalso have arangemethod that finds a particular substring in a string.You can create your desired range by using the
..<operator on thelowerBoundandupperBoundof the found ranges of "sip:" and "@".You can then pass the range to the
Stringsubscript to get the result as aSubstring.If I understand correctly, the logic you want is: