10

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

matzino
  • 3,544
  • 1
  • 18
  • 37
  • 8
    Most functions that used to return a range with `NSNotFound` now return an optional Range instead. So it should be enough to check that the range is not `nil`. – Fogmeister Jan 06 '17 at 16:26
  • Good to know! In my case it is a self created range over a Data-Object (previously NSData), therefore the nil check doesn't work. – matzino Jan 06 '17 at 16:37
  • 5
    If it's a function you've written yourself then change it to return an optional ;-) – Fogmeister Jan 06 '17 at 16:38

1 Answers1

3

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"
}
odyth
  • 4,324
  • 3
  • 37
  • 45