Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Array contains ClosedRange?

In my application written in Swift 4.2 I have the following code:

let arrayOfIntegers = [2, 1, 9, 5, 4, 6, 8, 7]
let unknownLowerBound = 4
let unknownUpperBound = 20
let closedRange = ClosedRange<Int>(uncheckedBounds: (lower: unknownLowerBound,
                                                     upper: unknownUpperBound))
let subRange = arrayOfIntegers[closedRange]
subRange.forEach { print($0) }

As you can guess when I am running this code I receive the following error: Fatal error: Array index is out of range. I want to prevent it.

like image 767
Roman Podymov Avatar asked Dec 12 '25 07:12

Roman Podymov


1 Answers

You can check if the range of valid array indices “clamped” to the given closed range is equal to that range:

let array = [1, 2, 3, 4, 5, 6, 7, 8]
let closedRange = 4...20
if array.indices.clamped(to: Range(closedRange)) == Range(closedRange) {
    let subArray = array[closedRange]
    print(subArray)
} else {
    print("closedRange contains invalid indices")
}

Or, equivalently:

if array.indices.contains(closedRange.lowerBound)
    && array.indices.contains(closedRange.upperBound) {
    // ...
}
like image 141
Martin R Avatar answered Dec 14 '25 00:12

Martin R