Foreign reference types (ForeignReferenceType)
Warnings related to foreign reference types imported from C and C++.
Overview
Swift imports C and C++ types annotated with SWIFT_SHARED_REFERENCE as foreign reference types (FRTs). Their memory is managed in a similar manner to native Swift classes: the compiler automatically inserts calls to retain and release operations that maintain an FRT’s reference count.
When a Swift program calls a foreign function returning an FRT, the compiler relies on ownership convention annotations to determine whether it needs to insert a retain call on behalf of the Swift program:
SWIFT_RETURNS_RETAINEDmeans the FRT is returned as an owned object (+1 reference count)SWIFT_RETURNS_UNRETAINEDmeans the FRT is returned as an unowned object (+0 reference count)
Without these annotations, the compiler can generate code with a superfluous or missing retain call that leads to memory leaks and errors, so it emits the following warning:
warning: cannot infer ownership of foreign reference value returned by 'returnsFRT()'Fixing the warning
To address these warnings, you should add the appropriate annotation to your C or C++ function declaration:
// Returns a retained (+1) object
SWIFT_RETURNS_RETAINED MyFRT* createObject();
// Returns an unretained (+0) object
SWIFT_RETURNS_UNRETAINED MyFRT* getExistingObject();Objective-C and Objective-C++ methods can be similarly annotated:
// Returns a retained (+1) object
- (MyFRT *)createObject SWIFT_RETURNS_RETAINED;
// Returns an unretained (+0) object
- (MyFRT *)getExistingObject SWIFT_RETURNS_UNRETAINED;See Also
@dynamicCallable implementation requirements (DynamicCallable)Add @preconcurrency import (AddPreconcurrencyImport)Always enabled availability domains (AlwaysAvailableDomain)Argument matching for trailing closures (TrailingClosureMatching)Calling a mutating async actor-isolated method (ActorIsolatedMutatingAsync)Calling an actor-isolated method from a synchronous nonisolated context (ActorIsolatedCall)Captures in a `@Sendable` closure (SendableClosureCaptures)Compilation caching (CompilationCaching)Conforming to `StringInterpolationProtocol` (StringInterpolationConformance)Conversion from `@isolated(any)` function type to synchronous function type (ConversionFromIsolatedAnyToSynchronous)Cross-isolation data race (RegionIsolationCrossIsolationDataRace)Deprecated declaration warnings (DeprecatedDeclaration)Deprecated implementation-only imports (ImplementationOnlyDeprecated)Dynamic exclusivity (DynamicExclusivity)Embedded Swift language restrictions (EmbeddedRestrictions)