Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent value for NSRange.location on the Range Object within Swift 3?

Did someone can give me a hint which property of a Range is the equivalent property to the location property of an NSRange.

Especially I'm interested how I would migrate the following line of code from Swift 2.3 -> Swift 3.0

if myRange.location != NSNotFound { ... }

myRange is still a Range property and so the compiler tells me correct: Value of Type Range has no member location

Is it enough to check the empty property?

if !myRange.isEmpty { ... }

Thanks in advance

like image 797
matzino Avatar asked Jan 06 '17 16:01

matzino


People also ask

What is NSRange in Swift?

A structure used to describe a portion of a series, such as characters in a string or objects in an array.

How do you find the range in Swift?

Ranges with Strings< range operators are a shorthand way of creating ranges. For example: let myRange = 1..<3. let myRange = CountableRange<Int>(uncheckedBounds: (lower: 1, upper: 3)) // 1..<3.

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.


1 Answers

Like the comments say, instead of returning NSNotFound you will get a nil range.

To answer your question though .location has been replaced with .lowerBound and .upperBound.

let s = "The yellow dog is nice"
if let range = s.range(of: "dog")
{
    print(s[range.lowerBound...]) //prints "dog is nice"
    print(s[range.upperBound...]) //prints " is nice"
    print(s[range.lowerBound..<range.upperBound]) //prints "dog"
}
like image 143
odyth Avatar answered Nov 08 '22 16:11

odyth