Skip to content

Commit 3e61893

Browse files
authored
Merge pull request #26200 from atrick/doc-unsaferefcast
2 parents 5bf0cf6 + e75f551 commit 3e61893

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

docs/StandardLibraryProgrammersManual.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,19 @@ TODO: Should this subsume or link to [AccessControlInStdlib.rst](https://github.
5050

5151
Optionals can be unwrapped with `!`, which triggers a trap on nil. Alternatively, they can be `.unsafelyUnwrapped()`, which will check and trap in debug builds of user code. Internal to the standard library is `._unsafelyUnwrappedUnchecked()` which will only check and trap in debug builds of the standard library itself. These correspond directly with `_precondition`, `_debugPrecondition`, and `_sanityCheck`. See [that section](#precondition) for details.
5252

53+
#### UnsafeBitCast and Casting References
54+
55+
In general `unsafeBitCast` should be avoided because it's correctness relies on subtle assumptions that will never be enforced, and it indicates a bug in Swift's type system that should be fixed. It's less bad for non-pointer trivial types. Pointer casting should go through one of the memory binding API instead as a last resort.
56+
57+
Reference casting is more interesting. References casting can include converting to an Optional reference and converting from a class constrained existential.
58+
59+
The regular `as` operator should be able to convert between reference types with full dynamic checking.
60+
61+
`unsafeDownCast` is just as capable, but is only dynamically checked in debug mode or if the cast requires runtime support.
62+
63+
`_unsafeUncheckedDowncast` is the same but is only dynamically checked in the stdlib asserts build, or if the cast requires runtime support.
64+
65+
`_unsafeReferenceCast` is only dynamically checked if the cast requires runtime support. Additionally, it does not impose any static `AnyObject` constraint on the incoming reference. This is useful in a generic context where the object-ness can be determined dynamically, as done in some bridged containers.
5366

5467
### Builtins
5568

0 commit comments

Comments
 (0)