What does Swift 6.2's -strict-memory-safety flag report, and what do the unsafe expression and the @unsafe and @safe attributes do?
answer
- opt-in, warnings only
- like try, but for unsafety
- a group you can escalate
- encapsulate behind @safe
basics
~20 sSince Swift 6.2, -strict-memory-safety adds warnings wherever code uses unsafe constructs such as Unsafe pointer types, unowned(unsafe) or unsafeBitCast. Mark each use with an unsafe expression, mark unsafe APIs @unsafe, or declare a type @safe when it hides unsafe storage.
solid answer
~40 s`-strict-memory-safety` (SE-0458, Swift 6.2) is an opt-in mode, separate from the Swift 6 language mode. It adds no run-time checks; it reports warnings in the `StrictMemorySafety` diagnostic group at every use of an unsafe construct: declarations marked `@unsafe` such as `UnsafePointer`, `UnsafeRawBufferPointer` and `unsafeBitCast`, anything whose type involves them, `unowned(unsafe)`, `nonisolated(unsafe)` and `@exclusivity(unchecked)`. You acknowledge a use with the **`unsafe` expression**, which works like `try`: it covers one expression and does not propagate outward. `@unsafe` marks your own declaration or conformance as unsafe to use; `@safe` says a type that stores unsafe values presents a safe interface. `-Werror StrictMemorySafety` turns the warnings into errors.
code
bash · 2 linesxcrun swiftc -swift-version 5 -strict-memory-safety -typecheck Parser.swift
xcrun swiftc -swift-version 5 -strict-memory-safety -Werror StrictMemorySafety -typecheck Parser.swiftgo deeper
Recall that the mode is opt-in and only warns, and that unsafe in front of an expression acknowledges the unsafe operations in it.
Explain the difference between the unsafe expression, @unsafe on a declaration and @safe on an encapsulating type, and why unsafe does not propagate like try.
Know what the mode flags beyond pointers, unowned(unsafe), nonisolated(unsafe) and @exclusivity(unchecked), and how -Werror StrictMemorySafety turns it into a gate.
Decide which modules should build with the mode, typically those parsing untrusted input, and whether its warnings become errors there.
## What the mode is Swift is memory-safe by default for lifetime, bounds, type and initialization, yet it deliberately includes **unsafe constructs**: the `Unsafe` pointer types, `unowned(unsafe)`, `nonisolated(unsafe)`, `unsafeBitCast`, and C interoperability. **Strict memory safety** (SE-0458, Swift 6.2) is an **opt-in** mode that makes every use of those constructs visible. - Turn it on with the compiler flag **`-strict-memory-safety`**. - It is **not** part of the Swift 6 language mode; `-swift-version 6` alone does not enable it. - It produces **warnings only**, in the diagnostic group **`StrictMemorySafety`**. Escalate them with `-Werror StrictMemorySafety`. - It adds **no run-time checks**. It is an audit of the source. ## What it reports A typical warning is: `warning: expression uses unsafe constructs but is not marked with 'unsafe'` with a note naming the reason. Swift 6.4 reports, among others: - a use of a declaration marked **`@unsafe`** — the standard library marks `UnsafePointer`, `UnsafeMutablePointer`, `UnsafeRawBufferPointer`, `unsafeBitCast` and others; - a use of anything whose **type involves** an unsafe type, such as calling `loadUnaligned` on an `UnsafeRawBufferPointer`; - a use of an **`unowned(unsafe)`**, **`nonisolated(unsafe)`** or **`@exclusivity(unchecked)`** declaration; - a type whose **stored properties** involve unsafe types: `struct 'ByteWindow' has storage involving unsafe types`; - an `@unsafe` member used to satisfy a safe protocol requirement. ## Acknowledging unsafe code There are three ways to silence a warning, and each one says something different: 1. **The `unsafe` expression** — `unsafe raw.loadUnaligned(as: UInt32.self)` — acknowledges unsafe operations inside one expression, the way `try` marks a throwing call. Unlike `try`, it does **not** propagate outward: the function containing it does not become `@unsafe`, and a `withUnsafeBytes` call whose closure contains it needs no marker of its own. 2. **`@unsafe`** on your own declaration says *callers* must treat it as unsafe. It also marks a conformance: `struct MyType: @unsafe CustomStringConvertible`. 3. **`@safe`** on a type or declaration says it **encapsulates** unsafe parts behind a safe interface. `Array.withUnsafeBytes` is `@safe`: the array guarantees the buffer it lends, and responsibility moves to the closure. `Span` is also declared `@safe`. For a struct that stores an `UnsafeRawBufferPointer`, the compiler's notes offer exactly two choices: *add '@safe' if this type encapsulates the unsafe storage in a safe interface* or *add '@unsafe' if this type is also unsafe to use*. ## Outside the mode The `unsafe` keyword is accepted without the flag; it is a contextual keyword, so code that already uses `unsafe` as an identifier generally keeps compiling. Without the flag the only related warning is `no unsafe operations occur within 'unsafe' expression`, when the marker covers nothing unsafe. ## Adopting it in an existing module 1. Build once with `-strict-memory-safety` and read the warnings with their notes; most point at a handful of pointer-heavy files. 2. Mark each acknowledged use with `unsafe`, keeping each marker as narrow as one expression so a reader sees exactly what is unsafe. 3. For each type with unsafe storage, decide whether it is `@safe` (it checks bounds and lifetime itself) or `@unsafe` (callers must take care). 4. Escalate with `-Werror StrictMemorySafety` once the module is clean, so new unsafe code needs an explicit marker. The proposal expects fix-its to apply the markers mechanically; deciding what each marker is allowed to cover is the part that needs review. ## Where it fits | Tool | What it checks | When | |---|---|---| | Exclusivity enforcement | overlapping accesses | compile time and run time, on by default | | Bounds checks on `Array` and `Span` | index ranges | run time, kept in `-O` | | `-strict-memory-safety` | where unsafe constructs are used | compile time, opt-in | | Swift 6 language mode | data races between concurrent code | compile time | The mode suits security-sensitive modules, such as parsers of untrusted input: it turns "where do we use unsafe pointers?" into a list the compiler maintains. Swift 6.4 tightened the standard library's own annotations, marking `Span.bytes` and `MutableSpan.mutableBytes` `@unsafe`.
- Does Swift's unsafe expression propagate to the enclosing function the way try does?No. `try` forces the enclosing function to be `throws` or to catch, but `unsafe` only acknowledges the unsafe operations in its own expression. The function containing it is not implicitly `@unsafe`, and a call such as `withUnsafeBytes` whose closure uses `unsafe` needs no marker.
- Does Swift's -strict-memory-safety make unsafe pointer code safer at run time?No. It adds no run-time checks; it only reports where unsafe constructs are used and requires each use to be acknowledged. Bounds, lifetime and alignment remain the programmer's job wherever `Unsafe` pointers are used.
- Strict memory safety is turned on automatically by the Swift 6 language mode.
- The flag adds run-time bounds checks to UnsafeBufferPointer.
- Using unsafe inside a function makes the whole function @unsafe.
- @safe makes the compiler verify that a type's pointer use is correct.
- The unsafe keyword is a syntax error unless the flag is on.
Assumes Swift 6.2 or later: SE-0458 added the opt-in -strict-memory-safety mode in 6.2; it is not enabled by -swift-version 6.