Swift Proposal: Opt-in Strict Memory Safety Checking
For example, Swift solves null references with optional types. Statically, Swift prevents you from using an optional reference without checking it first. If you’re sure it’s non-null, you can use the
!
operator, which is safe because Swift will dynamically check fornil
. If you really can’t afford that dynamic check, you can useunsafelyUnwrapped
. This can still be correct if you can prove that the reference is definitely non-null for some reason that Swift doesn’t know. But it is an unsafe feature because it admits violations if you’re wrong.[…]
A compiler flag
-strict-memory-safety
that enables warnings for all uses of unsafe constructs within a given module. All warnings will be in the diagnostic groupUnsafe
, enabling precise control over memory-safety-related warnings per SE-0443. When strict memory safety is enabled, theStrictMemorySafety
feature will be set:#if hasFeature(StrictMemorySafety)
can be used to detect when Swift code is being compiled in this mode.[…]
Because
UnsafeBufferPointer
andUnsafePointer
are@unsafe
types, this code will get a warning regardless of whether the declarations were marked@unsafe
, because having unsafe types in the signature of a declaration implies that they are@unsafe
. This helps us identify more unsafe code even when the libraries we depend on haven’t enabled strict safety checking themselves.To suppress these warnings, the expressions involving unsafe code must be marked with
unsafe
in the same manner as one would mark a throwing expression withtry
or an asynchronous expression withasync
.
Previously:
- Swift Proposal: Precise Control Flags Over Compiler Warnings
- Swift Vision: Improving the Approachability of Data-Race Safety
- Unwanted Swift Concurrency Checking
- The Evolution of “safe” and “unsafe” in Swift
- Swift 5 Exclusivity Enforcement
- Why Safe C Is Sometimes Unsafe Swift