Source-level warning control

The @diagnose attribute

@diagnose refines compiler warning behavior inside a specific declaration. It lets a focused region of source code be stricter or more permissive than the rest of its module.

Think of it as a scoped warning policy. Choose a diagnostic group, select its behavior, and apply that policy only where it makes sense.

At a glance

@diagnose(
    StrictMemorySafety,
    as: error,
    reason: "Security-sensitive boundary"
)
func decodeHeader(_ pointer: UnsafePointer<UInt8>) {
    // StrictMemorySafety warnings are errors throughout
    // this declaration's signature and lexical scope.
}

Parameters

Parameter Type Purpose Possible values
Diagnostic group ID Identifier Selects the warning group whose behavior changes in this declaration. See Documented diagnostic groups.
as: Behavior specifier Defines how warnings from the selected group are emitted. error, warning, or ignored.
reason: Optional static string literal Documents why the warning behavior differs in this declaration. Any string literal without interpolation.

Behavior effects

The value passed to as: determines the selected group’s behavior throughout the declaration:

Behavior Effect inside the declaration
error Promotes warnings in the selected group to errors.
warning Emits the selected group as warnings, even when an enclosing or module-wide policy promoted them to errors.
ignored Suppresses warnings in the selected group within the declaration.

How scope works

The policy covers both the annotated declaration’s signature and its lexical scope. It can be applied to functions, types, extensions, protocols, initializers, subscripts, computed properties, accessors, observers, enum cases, type aliases, associated types, imports, and declarations produced by freestanding declaration macros.

@diagnose(StrictMemorySafety, as: warning)
struct LegacyDecoder {
    func decode(_ pointer: UnsafePointer<UInt8>) {
        // StrictMemorySafety diagnostics are warnings here.
    }

    @diagnose(
        StrictMemorySafety,
        as: ignored,
        reason: "Input is validated by the caller"
    )
    func decodeTrusted(_ pointer: UnsafePointer<UInt8>) {
        // The nested declaration overrides its enclosing policy.
    }
}

Nested declarations can refine an enclosing policy. The innermost policy wins. Multiple attributes on the same declaration are order-sensitive, and the lexically last applicable attribute wins.

Relationship with build settings

Module-wide flags such as -warnings-as-errors, -Werror <GroupID>, and -Wwarning <GroupID> establish global behavior. @diagnose overrides that behavior for its declaration only.

// The module uses: -warnings-as-errors
@diagnose(
    ErrorInFutureSwiftVersion,
    as: warning,
    reason: "Migration is tracked for this compatibility layer"
)
func compatibilityLayer() {
    // Future-version diagnostics remain visible without failing this build.
}

Important limits:

Use cases

Allow a temporary deprecated API exception

A project can enforce deprecation warnings as errors globally while allowing one compatibility boundary to keep building. The reason: records why the exception exists and when it should be revisited.

@diagnose(
    DeprecatedDeclaration,
    as: warning,
    reason: "Maintain compatibility until the next release"
)
func bridgeToLegacySystem() {
    oldAPI() // Remains a warning here instead of an error.
}

Prepare a declaration for a future Swift language mode

Promote warnings that will become errors in a future Swift language mode today. This helps teams migrate sensitive or actively maintained code before changing the entire module’s language mode.

@diagnose(
    ErrorInFutureSwiftVersion,
    as: error,
    reason: "Keep this parser ready for the next Swift language mode"
)
func parseConfiguration() {
    // Future-version errors already fail this declaration's build.
}

Keep generated or compatibility code free of unused values

Treat unused values as errors inside declarations where every computed result should be consumed, without imposing that policy throughout the project.

@diagnose(NoUsage, as: error)
func generateBindings() {
    buildMetadata() // Fails the build if this result is unused.
}

These are only a few possible policies. Explore all available identifiers in Documented diagnostic groups.

Documented diagnostic groups

The table covers every Group ID with a corresponding document in Swift’s diagnostic documentation at commit aacc248. Each ID links to its source document.

The snippets demonstrate how to apply each identifier. Whether a snippet produces a diagnostic depends on the code inside the declaration, compiler version, language mode, enabled features, and build settings. @diagnose only affects diagnostics emitted as warnings; it cannot modify compiler errors.

Group IDDescriptionSwift usage
ActorIsolatedCallCalling actor-isolated methods from synchronous nonisolated contexts
@diagnose(ActorIsolatedCall, as: error)
func scopedCheck() { ... }
ActorIsolatedMutatingAsyncCalling mutating async actor-isolated methods
@diagnose(ActorIsolatedMutatingAsync, as: error)
func scopedCheck() { ... }
AddPreconcurrencyImportAdd @preconcurrency imports
@diagnose(AddPreconcurrencyImport, as: error)
import SomeModule
AlwaysAvailableDomainAlways-enabled availability domains
@diagnose(AlwaysAvailableDomain, as: error)
func scopedCheck() { ... }
AvailabilityUnrecognizedNameUnrecognized availability platforms
@diagnose(AvailabilityUnrecognizedName, as: error)
func scopedCheck() { ... }
CanImportMissingModuleMissing modules referenced by canImport
@diagnose(CanImportMissingModule, as: error)
import SomeModule
ClangDeclarationImportImported Clang declaration warnings
@diagnose(ClangDeclarationImport, as: error)
import SomeModule
CompilationCachingCompilation caching diagnostics
@diagnose(CompilationCaching, as: error)
func scopedCheck() { ... }
ConformanceIsolationProtocol conformances crossing into actor-isolated code
@diagnose(ConformanceIsolation, as: error)
func scopedCheck() { ... }
ConversionFromIsolatedAnyToSynchronousConversions from @isolated(any) to synchronous functions
@diagnose(ConversionFromIsolatedAnyToSynchronous, as: error)
func scopedCheck() { ... }
DeprecatedDeclarationUses of deprecated declarations
@diagnose(DeprecatedDeclaration, as: error)
func scopedCheck() { ... }
DynamicCallable@dynamicCallable implementation requirements
@diagnose(DynamicCallable, as: error)
func scopedCheck() { ... }
DynamicExclusivityDynamic exclusivity checks
@diagnose(DynamicExclusivity, as: error)
func scopedCheck() { ... }
EmbeddedRestrictionsEmbedded Swift language restrictions
@diagnose(EmbeddedRestrictions, as: error)
func scopedCheck() { ... }
ErrorInFutureSwiftVersionWarnings that become errors in a future Swift mode
@diagnose(ErrorInFutureSwiftVersion, as: error)
func scopedCheck() { ... }
ExclusivityViolationOverlapping access violations
@diagnose(ExclusivityViolation, as: error)
func scopedCheck() { ... }
ExistentialAnyExplicit any for existential types
@diagnose(ExistentialAny, as: error)
func scopedCheck() { ... }
ExistentialMemberAccessExistential member access limitations
@diagnose(ExistentialMemberAccess, as: error)
func scopedCheck() { ... }
ExistentialTypeExistential type performance hints
@diagnose(ExistentialType, as: error)
func scopedCheck() { ... }
ExplicitSendableExplicit Sendable annotations on public types
@diagnose(ExplicitSendable, as: error)
func scopedCheck() { ... }
ForeignReferenceTypeForeign reference types
@diagnose(ForeignReferenceType, as: error)
func scopedCheck() { ... }
ImplementationOnlyDeprecatedDeprecated implementation-only imports
@diagnose(ImplementationOnlyDeprecated, as: error)
import SomeModule
ImplicitStrongCaptureImplicit strong captures of weak items
@diagnose(ImplicitStrongCapture, as: error)
func scopedCheck() { ... }
InconsistentImportAccessInconsistent import access levels
@diagnose(InconsistentImportAccess, as: error)
import SomeModule
IsolatedConformancesIsolated conformances
@diagnose(IsolatedConformances, as: error)
func scopedCheck() { ... }
MemberImportVisibilityMember import visibility
@diagnose(MemberImportVisibility, as: error)
import SomeModule
MissingModuleOnKnownPathsMissing modules on known dependency paths
@diagnose(MissingModuleOnKnownPaths, as: error)
func scopedCheck() { ... }
ModuleNotTestableModules unavailable for testing
@diagnose(ModuleNotTestable, as: error)
func scopedCheck() { ... }
ModuleSelfImportA module importing itself
@diagnose(ModuleSelfImport, as: error)
import SomeModule
ModuleVersionMissingMissing module versions
@diagnose(ModuleVersionMissing, as: error)
func scopedCheck() { ... }
MultipleInheritanceUnsupported multiple inheritance
@diagnose(MultipleInheritance, as: error)
func scopedCheck() { ... }
MutableGlobalVariableUnsafe mutable global and static variables
@diagnose(MutableGlobalVariable, as: error)
func scopedCheck() { ... }
NoUsageUnused values
@diagnose(NoUsage, as: error)
func scopedCheck() { ... }
NoUseUnstructuredThrowingTaskUnused throwing unstructured tasks
@diagnose(NoUseUnstructuredThrowingTask, as: error)
func scopedCheck() { ... }
NominalTypesNominal type diagnostics
@diagnose(NominalTypes, as: error)
func scopedCheck() { ... }
NonisolatedNonsendingByDefaultnonisolated(nonsending) default behavior
@diagnose(NonisolatedNonsendingByDefault, as: error)
func scopedCheck() { ... }
OldSuppressedAssociatedTypesMigration from suppressed associated types
@diagnose(OldSuppressedAssociatedTypes, as: error)
func scopedCheck() { ... }
OpaqueTypeInferenceOpaque result type inference
@diagnose(OpaqueTypeInference, as: error)
func scopedCheck() { ... }
OptionObsoletedByModuleSelectorsOptions obsoleted by module selectors
@diagnose(OptionObsoletedByModuleSelectors, as: error)
func scopedCheck() { ... }
OSLogOSLog module diagnostics
@diagnose(OSLog, as: error)
func scopedCheck() { ... }
PerformanceHintsPerformance-related hints
@diagnose(PerformanceHints, as: error)
func scopedCheck() { ... }
PreconcurrencyImportExtraneous @preconcurrency imports
@diagnose(PreconcurrencyImport, as: error)
import SomeModule
PropertyWrappersProperty wrapper implementation requirements
@diagnose(PropertyWrappers, as: error)
func scopedCheck() { ... }
ProtocolTypeNonConformanceProtocol types that cannot conform to protocols
@diagnose(ProtocolTypeNonConformance, as: error)
func scopedCheck() { ... }
PublicImportOfProjectInternalModulePublic imports of project-internal modules
@diagnose(PublicImportOfProjectInternalModule, as: error)
import SomeModule
RegionIsolationCrossIsolationDataRaceCross-isolation data races
@diagnose(RegionIsolationCrossIsolationDataRace, as: error)
func scopedCheck() { ... }
RegionIsolationUnknownPatternUnknown region-isolation patterns
@diagnose(RegionIsolationUnknownPattern, as: error)
func scopedCheck() { ... }
ResultBuilderMethodsResult builder method requirements
@diagnose(ResultBuilderMethods, as: error)
func scopedCheck() { ... }
ReturnTypeImplicitCopyImplicit copies on return
@diagnose(ReturnTypeImplicitCopy, as: error)
func scopedCheck() { ... }
SemanticCopiesSemantic copy diagnostics
@diagnose(SemanticCopies, as: error)
func scopedCheck() { ... }
SendableClosureCapturesCaptures in @Sendable closures
@diagnose(SendableClosureCaptures, as: error)
func scopedCheck() { ... }
SendableMetatypesSendable metatypes
@diagnose(SendableMetatypes, as: error)
func scopedCheck() { ... }
SendingClosureRisksDataRaceSending closures that risk data races
@diagnose(SendingClosureRisksDataRace, as: error)
func scopedCheck() { ... }
SendingRisksDataRaceSending values that risk data races
@diagnose(SendingRisksDataRace, as: error)
func scopedCheck() { ... }
SPIImportIgnoredIgnored SPI imports
@diagnose(SPIImportIgnored, as: error)
import SomeModule
StrictLanguageFeaturesStrict language feature enablement
@diagnose(StrictLanguageFeatures, as: error)
func scopedCheck() { ... }
StrictMemorySafetyStrict memory-safety checks
@diagnose(StrictMemorySafety, as: error)
func scopedCheck() { ... }
StringInterpolationConformanceStringInterpolationProtocol conformances
@diagnose(StringInterpolationConformance, as: error)
func scopedCheck() { ... }
TemporaryPointersTemporary pointer lifetime issues
@diagnose(TemporaryPointers, as: error)
func scopedCheck() { ... }
TrailingClosureMatchingTrailing-closure argument matching
@diagnose(TrailingClosureMatching, as: error)
func scopedCheck() { ... }
UnavailableSendableConformanceUnavailable Sendable conformances
@diagnose(UnavailableSendableConformance, as: error)
func scopedCheck() { ... }
UnknownWarningGroupUnknown warning groups
@diagnose(UnknownWarningGroup, as: error)
func scopedCheck() { ... }
UnnecessaryEffectMarkerUnnecessary effect markers
@diagnose(UnnecessaryEffectMarker, as: error)
func scopedCheck() { ... }
UnnecessaryUnsafeUnnecessary unsafe markers
@diagnose(UnnecessaryUnsafe, as: error)
func scopedCheck() { ... }
UnrecognizedStrictLanguageFeaturesUnrecognized strict language features
@diagnose(UnrecognizedStrictLanguageFeatures, as: error)
func scopedCheck() { ... }
UnsupportedScopedImportUnsupported scoped imports
@diagnose(UnsupportedScopedImport, as: error)
import SomeModule
UntypedThrowsUntyped throws
@diagnose(UntypedThrows, as: error)
func scopedCheck() { ... }
UnusedImportAccessUnused import access levels
@diagnose(UnusedImportAccess, as: error)
import SomeModule
UseAnyAppleOSAvailabilityUse of anyAppleOS availability
@diagnose(UseAnyAppleOSAvailability, as: error)
func scopedCheck() { ... }
UselessAvailabilityCheckAvailability checks with no effect
@diagnose(UselessAvailabilityCheck, as: error)
func scopedCheck() { ... }
UselessConditionalStatementConditional statements with no effect
@diagnose(UselessConditionalStatement, as: error)
func scopedCheck() { ... }

References