Roman Podymov
Roman Podymov

Reputation: 4521

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.

Upvotes: 3

Views: 968

Answers (2)

onmyway133
onmyway133

Reputation: 48095

To check for ClosedRange<Int> and Range<Int>

Remember that Range does not include the upperBound

private extension Array {
    func contains(range: ClosedRange<Int>) -> Bool {
        indices.contains(range.lowerBound) && indices.contains(range.upperBound)
    }
}
private extension Array {
    func contains(range: Range<Int>) -> Bool {
        range.lowerBound >= 0 && range.upperBound <= count
    }
}

Upvotes: 1

Martin R
Martin R

Reputation: 539795

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) {
    // ...
}

Upvotes: 6

Related Questions