TIL in Swift `unsafeBitCast(_:to:)`, `type(of:)`, `withoutActuallyEscaping(_:do:)`, 'OpaquePointer', `MemoryLayout`, `offset(of:)`, `AutoreleasingUnsafeMutablePointer`
While exploring pointer stuff in Swift read about unsafeBitCast(_:to:)
but acually I read declarations inside Xcode. As always it’s extremely interesting to read in Swift source code in Xcode because there you always see real declarations along with related stuff.
Then jumped to type(of:)
where I barely understood second part about generic context.
Then jumped to withoutActuallyEscaping(_:do:)
.
Then jumped to ‘OpaquePointer’. That’s simple:
Opaque pointers are used to represent C pointers to types that cannot be represented in Swift, such as incomplete struct types.
Then jumpled to MemoryLayout
. Everything is clear but this is a little obscure:
Always use a multiple of a type’s
stride
instead of itssize
when allocating memory or accounting for the distance between instances in memory.
Hm, I didn’t know that type’s alignment
should be used when allocating memory using an unsafe pointer. But when accessing memory stride
should be used.
And offset(of:)
is something I don’t fully understand.
Found out strange thing which I have never met in wild AutoreleasingUnsafeMutablePointer
:
This type has implicit conversions to allow passing any of the following to a C or ObjC API:
-
nil
, which gets passed as a null pointer, -
an inout argument of the referenced type, which gets passed as a pointer to a writeback temporary with autoreleasing ownership semantics,
-
an
UnsafeMutablePointer<Pointee>
, which is passed as-is.