如何检查Array是否包含ClosedRange?

时间:2018-11-08 10:41:49

标签: arrays swift range

在用Swift 4.2编写的应用程序中,我有以下代码:

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) }

您可以猜测我在运行此代码时会收到以下错误:Fatal error: Array index is out of range。我想阻止它。

1 个答案:

答案 0 :(得分:4)

您可以检查有效数组索引的范围是否“固定”为 给定的闭合范围等于该范围:

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")
}

或者,等效地:

if array.indices.contains(closedRange.lowerBound)
    && array.indices.contains(closedRange.upperBound) {
    // ...
}