Member-only story

Pointers in Swift

Prafulla Singh
4 min readJul 8, 2018

--

1. What is a pointer?

Read here : https://denniskubes.com/2017/01/24/the-5-minute-guide-to-c-pointers/

2. Unsafe operation in Swift

Most of Swift’s operations are safe, and Optional introduction is also for security. The compiler will help us to do static verification in most cases, a Int type can not be used as a String mass participation, a Optional type must be Unwrapped to safely use later.

But Swift also supports direct operations on memory, these operations are unsafe, so the API are covered with a Unsafe prefix, such as pointer UnsafePointer type.

Accessing array contents via subscripts is also an unsafe operation, such as:

let arr = []
let test = arr[1]

No error is reported at compile time, crash at runtime.

3. Memory Layout

C / C ++ in the common sizeof()keywords in Swift which was originally there, and sizeofValue, strideof, strideofValue, align and alignOf. In Swift 4, this is a bunch of "function" is wrapped into MemoryLayout this Struct inside, this is the time of the proposal .

And thus the information related to the memory alignment and the like are memory occupied by MemoryLayout acquiring, for example:

MemoryLayout<UInt32>.size // 4
MemoryLayout<UInt32>.alignment // 4
MemoryLayout<UInt32>.stride // 4

--

--

Prafulla Singh
Prafulla Singh

No responses yet