Pointers
A pointer is an object that stores a memory address. In Swift, there are 8 types of pointers. In Swift, pointers are known as UnsafePointer
because they support direct operations on memory and these operations are unsafe in nature that’s why a Unsafe
prefix is used with Pointers in swift.
They can be categories into the following types:
- Buffer type
- It stores elements contiguously in memory so that you can treat them like an array.
- Non-buffer type
- It points to a single element.
- Mutable type
- It allows mutating the memory referenced by that pointer.
- Immutable type
- It provides read-only access to the referenced memory.
- Raw type
- It contains uninitialized and untyped data.
- It must be bound to a certain type and value before we can use them.
- Typed pointers
- It takes a parameter, which is the type of value being pointed to.
- Unsafe type
- It doesn’t contain Swift’s safety features. It is possible to access unallocated memory or interpret memory as a wrong type by means of unsafe pointers.
- Managed type
- It has automatic memory management.
- an unmanaged type
- It makes you partially responsible for the object’s lifecycle.
Swift Unsafe Pointers
You use instances of the UnsafePointer
type to access data of a specific type in memory. The type of data that a pointer can access is the pointer’s Pointee
type. UnsafePointer
provides no automated memory management or alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior.
IMMUTABLE | MUTABLE |
UnsafePointer<T> |
UnsafeMutablePointer<T> |
UnsafeBufferPointer<T> |
UnsafeMutableBufferPointer<T> |
UnsafeRawPointer |
UnsafeMutableRawBufferPointer |
UnsafeRawBufferPointer |
UnsafeRawBufferPointer |
1 2 3 4 5 6 7 |
let ptr = UnsafeMutablePointer<Int>.allocate(capacity: 4) ptr.initialize(repeating: 1, count: 4) print(ptr.pointee) // 1 ptr[1] = 2 print(ptr[1]) // 2 |
pointee
It is used to accesses the instance referenced by this pointer.
1 |
var pointee: Pointee { get } |
When reading from the pointee
property, the instance referenced by this pointer must already be initialized.
Thank you for reading this article. If you want to read more articles regarding iOS Development click here or if you want to know more about the pointers click here.