如何测试索引是否超出 Swift 的范围?

How can you test that an index is out of range in Swift?

在单元测试中,我想断言可能抛出索引超出范围错误的方法实际上会抛出该错误。

我正在尝试使用

let array = [1,2,3]
XCTAssertThrowsError(array[3])    

为什么这不起作用?

我该如何测试?

let array = [1,2,3]
XCTAssertThrowsError(array[3])    

Why doesn't this work?

因为引用越界索引 不会 抛出。它崩溃,这是完全不同的事情。

How do I test this?

你如何测试什么?如果问题是建议的索引对于给定数组是否合法,请使用 indices.contains:

let array = [1,2,3]
let ix = 3
XCTAssert(array.indices.contains(ix), "Index out of bounds")