Instances of UnsafePointer<T>
and UnsafeMutablePointer<T>
are both mutable (if they are var
s), but only the latter is capable of mutating the memory that it points to.
let mp1 = UnsafeMutablePointer<UInt8>.allocate(capacity: 123)
var mp2 = UnsafeMutablePointer<UInt8>.allocate(capacity: 456)
var p = UnsafePointer<UInt8>(mp1)
p = UnsafePointer<UInt8>(mp2) // We can mutate the non-mutable pointer `p`,
mp2 = mp1 // just like we can mutate the mutable pointer `mp2`.
// One thing we cannot mutate is the memory that `p` points to:
// p.pointee = 123 // ERROR: Cannot assign to property: 'pointee' is a get-only property
// So `p` is a non-mutating pointer, not a non-mutable pointer.
// We can mutate the memory that `mp1` points to:
mp1.pointee = 78 // This is ok even though mp1 is a let constant, because
// it is not `mp1` that is mutable, it is the memory that it points to.
// And we cannot mutate `mp1` even though the name of its type is "ā¦Mutableā¦":
// mp1 = mp2 // ERROR: Cannot assign to value: 'mp1' is a 'let' constant
// So `mp1` is a mutating pointer, not a mutable pointer.
mp1.deallocate()
p.deallocate()