Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find previous and next Range in an array of NSRange

Array of NSRange: [{0, 31}, {32, 29}, {62, 10}, {73, 15}, {89, 0}, {90, 14}, {105, 22}, {128, 26}, {155, 15}, {171, 17}, {189, 22}, {212, 15}, {228, 18}, {247, 3}, {251, 2}, {254, 1}, {256, 0}, {257, 24}, {282, 22}]

myRange: {105, 148}

I have a range that it is not included necessarily in an array like "myRange"
I want to find the available range in the array that it is just before "myRange"
and the available range in the array that it is just after "myRange"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected : previous NSRange {90, 14} and
Next NSRange {254, 1}

Note: The upper bound of the range {105, 148} is 105 + 148 = 253, so I want next range lower bound to be greater than 253

>Solution :

To find the previous range you can use last(where:) and to find the next range you can use first(where:) on your NSRange array like this.

if let previous = nsRangeArray.last(where: { $0.upperBound < myRange.lowerBound }) {
    print(previous)
}
if let next = nsRangeArray.first(where: { $0.location > myRange.upperBound }) {
    print(next)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading