That's a fair question. Warning: Incoming Wall of Text!
It helps with escape analysis
Array
can escape its context, which means escape analysis must be performed and passed in order for it to be eligible for stack promotion. In the general case, escape analysis is undecidable. The compiler must often assume that, even for seemingly simple programs, values will escape their declaring contexts and so cannot be stack-promoted. This means that Array
, while safe to use, does not always produce optimal codegen. The proposed FixedCapacityArray
has the same problem: it can escape its calling context, so it must be subjected to escape analysis.
One common case where the compiler must assume an escape is possible is when a value is passed to a non-transparent function or closure: at that point, the compiler must assume that the value will escape. This limitation makes it very hard to use such a value in a complex project without sacrificing the performance benefits of stack promotion. The proposed unsafe function provides the ability to assert that the provided buffer cannot escape without violating the language's constraints (much like how the language trusts developers not to escape the pointer used in withUnsafeBytes(of:_:)
or to call UnsafeContinuation.resume(...)
more than once.)
It helps build safe, performant API
Unsafe primitives are important in a language like Swift because they are ultimately needed in order to build higher-level, safer constructs. For example, there are a number of C APIs (think POSIX) that write to pointers of various types but don't allocate or deallocate them themselves. Currently, there are really only two ways to use such API in Swift:
- Heap-allocate an
UnsafeMutable[Buffer]Pointer
or compatible type and pass it to the C API, or
- If only a single value is needed, pass a mutable
Optional
to the API with &
, which necessitates zero-initialization.
Both come with performance costs that this function is intended to resolve. Ideally, such API would get customized Swift interfaces that hide the need for unsafe pointers. A developer, working on the Swift interfaces for these C APIs, can use the proposed function to produce an optimal Swift interface that is as fast as using the C interface directly.
It's okay not to use it
This API is not for everyone. Like other APIs containing the word Unsafe
, it's expected that most engineers will rarely if ever use it. There are some engineers who will use it because it is necessary for them to complete the tasks in front of them. It's okay to be in the former group instead of the latter group.
For what it's worth, someone could conceivably create an "Extra-Safe Swift" that didn't expose any API for any unsafe constructs, and I think that's probably an area worth exploring in general. I'd be happy to add my two cents to a discussion thread about such a project.