Subscript array without bounds check?

In situations where the programmer needs the efficiency gained by skipping the bounds check of arr[i] (assuming they know for sure that i will always be within bounds of arr, but the optimizer has no way of proving it), is there a way to do eg:

arr[unchecked: i]

?

If not, would it make sense to add a subscript like that to Array and ContiguousArray or is there some other recommended way (without using pointers instead of arrays or doing an unchecked build)?

Perhaps the following will get the element at index i without any overhead (assuming release mode):

arr.withUnsafeBufferPointer { $0[i] }

?

Yes, that successfully elides the bounds check: Compiler Explorer

Or rather, it does on 4.1.x. I'm not entirely sure what's going on on master yet; there's a regression here that should be fixed ([SR-8773] Regression in codegen for bounds-check-avoiding subscript? · Issue #51281 · apple/swift · GitHub), but I don't know if it's in the stdlib or compiler yet.

Edit: nevermind, I was looking at a with-asserts build. This still works fine with normal builds.

5 Likes