[英]How to check if Array contains ClosedRange?
In my application written in Swift 4.2 I have the following code: 在我用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) }
As you can guess when I am running this code I receive the following error: Fatal error: Array index is out of range
. 您可以在运行此代码时猜出以下错误:
Fatal error: Array index is out of range
。 I want to prevent it. 我想防止它。
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) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.