I'm trying to understand the use of pointers in Swift, in particular: Unsafe[Mutable]Pointer
and UnsafeRaw[Mutable]Pointer
. I have several questions on the subject.
Is
UnsafePointer <T>
equal toconst T * Pointer
in ? andUnsafeMutablePointer <T>
is equal toT * Pointer
in C?What is the difference between
Unsafe[Mutable]Pointer
andUnsafeRaw[Mutable]Pointer
?Why does this compile
func receive(pointer: UnsafePointer<Int> ) {
print("param value is: \(pointer.pointee)")
}
var a: Int = 1
receive(pointer: &a) // prints 1
but this gives me an error?
var a: Int = 1
var pointer: UnsafePointer<Int> = &a // error : Cannot pass immutable value of type 'Int' as inout argument
var pointer: UnsafePointer<Int> = &a
was never valid, and your "workaround" is unsafe: The pointer passed to the closure ofwithUnsafePointer
is only valid during the execution of the closure. It must not be passed to the outside of the closure. – You cannot (safely) pass pointers to Swift variables freely around. – Forwardness