Memory Safety and Unsafe Swift

32.1 Exclusivity (Memory Safety)

Swift enforces exclusive access to memory: a write can't overlap another access to the same variable. It's checked at compile time and runtime.

var stepSize = 1
func increment(_ number: inout Int) { number += stepSize }
// increment(&stepSize)    // ❌ runtime error: simultaneous access (read stepSize while writing it)
var copy = stepSize
increment(&copy)
stepSize = copy

32.2 Unsafe Pointers

UnsafePointer<T> / UnsafeMutablePointer<T> UnsafeRawPointer / UnsafeMutableRawPointer

UnsafeBufferPointer<T> / UnsafeMutableBufferPointer<T> Pointer + count (a collection) Manual retain/release (C callbacks) Opaque C pointers Span, MutableSpan (6.2)

Swift 6.2 adds opt-in strict memory safety (-strict-memory-safety), which flags unsafe constructs that must be acknowledged with the unsafe keyword/expression.

var numbers = [1, 2, 3, 4]
numbers.withUnsafeMutableBufferPointer { buffer in
    for i in buffer.indices { buffer[i] *= 2 }
}

let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 4)
pointer.initialize(repeating: 0, count: 4)
pointer[2] = 42
pointer.deinitialize(count: 4)
pointer.deallocate()

let raw = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 8)
raw.storeBytes(of: UInt32(0xCAFEBABE), as: UInt32.self)
raw.deallocate()

withUnsafeBytes(of: 42) { bytes in print(Array(bytes)) }