Swift attributes & compiler directives — a catalogue

swift · folio

In one line: An attribute (@name(args)) changes how the compiler treats a declaration or type — what it exports, how it dispatches, what it checks — without changing its code; a directive (#if, #warning, #fileID…) acts at compile time on the source itself. The ones that matter most are about boundaries: module/ABI (@inlinable, @frozen), language (@objc), concurrency (@preconcurrency) and build configuration (#if).

Download PDF Print view LaTeX source

Swift attributes & compiler directives — a catalogue — figure 1

Library evolution & optimisation

@inlinablebody is part of the public interface; may use only public or @usableFromInline declarations
@usableFromInlineon internal/package: ABI-visible, source-invisible
@frozenpublic struct/enum: layout (or cases) fixed forever; ignored without library evolution
@backDeployed(before:)ships a copy of a new API into clients on older OSes (Apple SDK-style libraries)
@inline(__always) / (never)inlining hint / forbid (underscored, unofficial); @inline(always) (6.3, SE-0496) errors if a direct call can’t be inlined, implies @inlinable on public API

API surface

@discardableResultcallers may ignore the return value without a warning
@available(*, deprecated, renamed: "load(id:)")warning + Xcode fix-it; message:, unavailable (error), introduced:/obsoleted:, noasync
@available(iOS 17, *)callers must be in an if #available block or be gated themselves
@mainthe type’s static func main() (may be async throws) is the entry point; @UIApplicationMain is an error in Swift 6 mode (SE-0383)
@testable import Mtests see internal; needs ENABLE_TESTABILITY (Debug)
@_spi(Beta) publicvisible only to @_spi(Beta) import (underscored, unofficial)
packageaccess for modules of one package (5.9, SE-0386)
: @retroactive Pyou own neither type nor protocol (6.0, SE-0364)

Objective-C interop

@objc / @objc(name)exposed to the ObjC runtime (selectors, #selector, KVC)
@objcMembers@objc on every compatible member — incl. extensions and subclasses
@nonobjcopt one member out
@objc dynamicmessage dispatch via objc_msgSend: KVO, swizzling; dynamic alone is not KVO-observable
@convention(c) / (block)function type with a C / ObjC-block ABI

Concurrency & closures (details: concurrency sheets)

@preconcurrency import Mdowngrade Sendable diagnostics from an unmigrated module (5.6)
: @preconcurrency Pconformance whose isolation is checked at run time (6.0, SE-0423)
@unchecked Sendable“trust me”: no checking of stored properties — you own the locking
@TaskLocal static var idvalue bound per task tree: $id.withValue("r1") { … }; child tasks inherit, Task.detached doesn’t
@escaping @Sendable @MainActor ():=->Voidclosure type: may outlive the call · may run concurrently · runs on the main actor
nonisolated · (unsafe)opt a member out of its actor · opt out of checking
consuming / borrowingparameter ownership; consume x ends a lifetime, copy x copies explicitly (5.9)

Type roles, Interface Builder, Core Data

@propertyWrapper · @resultBuilderthe type becomes a wrapper / a DSL builder (own sheets)
@dynamicMemberLookup · @dynamicCallablex.name / x(1, 2) rewritten to subscripts / calls
@IBOutlet · @IBActionstoryboard connections; imply @objc
@NSManaged varCore Data supplies the accessors at run time
@NSCopying varthe setter stores newValue.copy()
@warn_unqualified_accesswarn unless called as self.min() — avoids the global min

Compiler directives

#if os(iOS) || os(visionOS)       // os arch canImport targetEnvironment
#if canImport(UIKit) && !targetEnvironment(macCatalyst)
#if targetEnvironment(simulator)  // simulator | macCatalyst
#if compiler(>=6.0)   // the COMPILER version (any language mode)
#if swift(>=6.0)      // the LANGUAGE MODE (-swift-version 6)
#if hasFeature(ExistentialAny)    // 5.8 SE-0362; hasAttribute(retroactive)
#if DEBUG             // your -D flag (SWIFT_ACTIVE_COMPILATION_CONDITIONS)
Text("Hi")
#if os(iOS)
  .padding()          // 5.5 SE-0308: #if around postfix members
#endif
#warning("TODO: remove")  // #error("...") stops the build
#sourceLocation(file: "gen.swift", line: 1)  // generated code maps back
#fileID    // "App/Feed.swift"; #file = #fileID in Swift 6 mode
#filePath  // full build-machine path - baked into the binary!
#function  // "load(id:)"   #line #column   #dsohandle: image handle
func run(isolation: isolated (any Actor)? = #isolation)  // caller's actor
macro stringify<T>(_ v: T) -> (T, String) =
  #externalMacro(module: "Macros", type: "StringifyMacro")

Traps

  • swift(:=>=6) is the language mode; a Swift 6 compiler in 5 mode fails it but passes compiler(:=>=6).
  • Inactive #if branches must still parse — except under swift()/compiler() checks.
  • @inlinable fixes reach clients only when they rebuild; @frozen is forever.
  • @unchecked Sendable silences the checker; it proves nothing.
  • @Observable, @Model look like attributes but are macros (they expand into code); @MainActor is a global-actor attribute.

Remember

“Attributes move boundaries: module (@inlinable, @frozen), language (@objc), isolation (@preconcurrency); #if moves code out of the build.”

Report a problem ·Discuss this folio