3

if case 1 : range1 is (5,10) and range2 is (8,0) it should return true. case 2 : range1 is (5,10) and range2 is (5,4) it should return true. case 3 if range1 is (5,10) and range2 is (14,20) it should return true. How to implement a function that return true for all cases. I want to check if a range intersect with another range or completely within it.

Aashish Nagar
  • 1,207
  • 1
  • 14
  • 30
  • 1
    http://stackoverflow.com/questions/10172688/objective-c-compare-range-intersect ? Shouldn't be big difficulties to adapt from Objective-C to Swift – Larme May 11 '17 at 13:39
  • `NSRange(8,0)` is an *empty* range, it does not overlap with anything. – Martin R May 11 '17 at 13:46
  • But this range falls within Range (5,10). I want to check falls condition as well. – Aashish Nagar May 11 '17 at 13:48
  • NSRange(8, 0) is the same as NSRange(30, 0) , so you cannot say that one of them intersects with (5,10) – Gerriet May 11 '17 at 13:51
  • @Gerriet No, those two ranges are not equal. They have the same length but not the same start. But `8,0` definitely intersects `(5,10)`. – rmaddy May 11 '17 at 13:53
  • 1
    @rmaddy: I see that differently. `NSRange(location: 8, length: 0)` describes the integers `x` satisfying `8 <= x < 8 + 0`, i.e. an empty range. `NSRange(location: 8, length: 0)` and `NSRange(location: 5, length: 10)` have no common elements. – Martin R May 11 '17 at 13:57
  • @MartinR I was thinking of it like an axis on a graph. I shouldn't have these discussions first thing in the morning (for me). I was thinking that the location `8` is within the range `5-15` and that the length of `0` was irrelevant. But I guess most uses of `NSRange` aren't used that way. – rmaddy May 11 '17 at 14:02
  • Thank you @MartinR . You got my point. – Aashish Nagar May 11 '17 at 14:06

1 Answers1

9

Range (the Swift way) has a method overlaps. If you want to work with NSRange it would be:

NSIntersectionRange(range1, range2).length > 0
Gerriet
  • 1,302
  • 14
  • 20