在我用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
。我想阻止它。 最佳答案
可以检查有效数组索引的范围是否“钳制”为
给定的闭合范围等于该范围:
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) {
// ...
}