2

I am having Swift code, need to get UpperBound and lowerBound. But in Objective C, I am not able to see the property or function for both Upper and lower Bound to get its value.

Snippet:

{
let upperBound =  firstAppearance?.upperBound;
let lowerBound =  firstAppearance?.lowerBound;
}

Where firstAppearence is Range.

Can anyone help me to get the Upper and lower Bound value from NSRange using Objective-C.

Jack
  • 13,571
  • 6
  • 76
  • 98

1 Answers1

4

NSRange is a simple struct with location and length. The closest equivalent you'll get to Swift's Range is:

NSUInteger lowerBounds = range.location;
NSUInteger upperBounds = range.location + range.length;

(N.B. This range contains the upper bound for non-empty ranges, unlike Swift's Range.)

Guy Kogus
  • 7,251
  • 1
  • 27
  • 32
  • Really? I thought that was the primary difference between `ClosedRange` and `Range`. `ClosedRange` will always contain the upper bound, `Range` only contains it if it's empty (according to the docs). – Guy Kogus Nov 07 '17 at 12:41
  • Actually I guess `NSRange` doesn't really "contain" a location, it's all about what kind of check you use. If you're using `NSLocationInRange` then my last statement is wrong. – Guy Kogus Nov 07 '17 at 12:43
  • `NSRange(location: a, length: b)` describes the half-open interval `[a, a+b)`, excluding the upper bound. – Martin R Nov 07 '17 at 12:46
  • I think Lower bound = range.location and upper bound = range.length. Because when I am printing swift Range it give me something like this: ▿ CountableRange(0..<65014) - lowerBound : 0 - upperBound : 65014 – Abilash Balasubramanian Nov 07 '17 at 13:07
  • @AbilashBNair then what happens if location is > 0? It's why you need `location + length`. – Guy Kogus Nov 08 '17 at 13:15