Sagar D
Sagar D

Reputation: 223

What is Swift alternative to NSRange.location and NSRange.length?

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])];
}

Upvotes: 0

Views: 78

Answers (1)

Sweeper
Sweeper

Reputation: 274480

Similar to the range method in NSString, Swift Strings also have a range method that finds a particular substring in a string.

You can create your desired range by using the ..< operator on the lowerBound and upperBound of the found ranges of "sip:" and "@".

You can then pass the range to the String subscript to get the result as a Substring.

If I understand correctly, the logic you want is:

func parseNameFrom(_ string: String) -> Substring? {
    let rangeOfSip = string.range(of: "sip:") ?? string.range(of: "sips:")
    if let rangeOfAt = string.range(of: "@") {
        if let rangeOfSip {
            return string[rangeOfSip.upperBound..<rangeOfAt.lowerBound]
        } else {
            return string[..<rangeOfAt.lowerBound]
        }
    } else {
        return nil // can't find it
    }
}

print(parseNameFrom("sip:[email protected]")!)

Upvotes: 3

Related Questions