Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of String.range in Swift 3.0

Tags:

ios

swift3

let us = "http://example.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.com)", options:.RegularExpressionSearch)
if range != nil {
    let found = us.substringWithRange(range!)
    print("found: \(found)") // found: example
}

This code extracts substring between backslashes and dot com in Swift 2. I searched Internet and I found that rangeOfString changed to range().

But still I could not make the code work in Swift 3.0. Could you help me ?

edit : I'm using swift 3 07-25 build.

like image 874
Fuzuli Avatar asked Aug 24 '16 14:08

Fuzuli


People also ask

What is range of string?

Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string.

How does range work in Swift?

Ranges in Swift allow us to select parts of Strings, collections, and other types. They're the Swift variant of NSRange which we know from Objective-C although they're not exactly the same in usage, as I'll explain in this blog post. Ranges allow us to write elegant Swift code by making use of the range operator.

What is Range expression in Swift?

In Swift, a range is a series of values between two numeric intervals. For example, var numbers = 1... 4. Here, ... is a range operator.


1 Answers

In swift 3.0 rangeOfString syntax changed like this.

let us = "http://example.com"
let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
if range != nil {
     let found = us.substring(with: range!)
     print("found: \(found)") // found: example
}
like image 61
Nirav D Avatar answered Oct 19 '22 23:10

Nirav D