API Notes: Annotations Without Modifying Headers#
The Problem: You have headers you want to use, but you also want to add extra information to the API. You donât want to put that information in the headers themselves â perhaps because you want to keep them clean for other clients, or perhaps because theyâre from some open source project and you donât want to modify them at all.
Incomplete solution: Redeclare all the interesting parts of the API in your own header and add the attributes you want. Unfortunately, this:
doesnât work with attributes that must be present on a definition
doesnât allow changing the definition in other ways
requires your header to be included in any client code to take effect
Better solution: Provide a âsidecarâ file with the information you want to add, and have that automatically get picked up by the module-building logic in the compiler.
Thatâs API notes.
API notes use a YAML-based file format. YAML is a format best explained by example, so here is a small example from the compiler test suite of API notes for a hypothetical âSomeKitâ framework.
Usage#
API notes files are found relative to the module map that defines a module, under the name âSomeKit.apinotesâ for a module named âSomeKitâ. Additionally, a file named âSomeKit_private.apinotesâ will also be picked up to go with a private module map. For bare modules these two files will be in the same directory as the corresponding module map; for framework modules, they should be placed in the Headers and PrivateHeaders directories, respectively. The module map for a private top-level framework module should be placed in the PrivateHeaders directory as well, though it does not need an additional â_privateâ suffix on its name.
Clang will search for API notes files next to module maps only when passed the
-fapinotes-modules option.
Limitations#
Since theyâre identified by module name, API notes cannot be used to modify arbitrary textual headers.
âVersionedâ API Notes#
Many API notes affect how a C API is imported into Swift. In order to change
that behavior while still remaining backwards-compatible, API notes can be
selectively applied based on the Swift compatibility version provided to the
compiler (e.g. -fapi-notes-swift-version=5). The rule is that an
explicitly-versioned API note applies to that version and all earlier
versions, and any applicable explicitly-versioned API note takes precedence
over an unversioned API note.
Reference#
An API notes file contains a YAML dictionary with the following top-level entries:
- Name:
The name of the module (the framework name, for frameworks). Note that this is always the name of a top-level module, even within a private API notes file.
Name: MyFramework
- Classes, Protocols, Tags, Typedefs, Globals, Enumerators, Functions, Namespaces:
Arrays of top-level declarations. Each entry in the array must have a âNameâ key with its Objective-C or C++ name. âTagsâ refers to structs, C++ classes, enums, and unions; âClassesâ refers to Objective-C classes; âEnumeratorsâ refers to enum cases.
Classes: - Name: MyController ⌠- Name: MyView âŚ
- SwiftVersions:
Contains explicit information for backwards compatibility. Each entry in the array contains a âVersionâ key, which should be set to â4â for annotations that only apply to Swift 4 mode and earlier. The other entries in this dictionary are the same declaration entries as at the top level: Classes, Protocols, Tags, Typedefs, Globals, Enumerators, and Functions.
SwiftVersions: - Version: 4 Classes: ⌠Protocols: âŚ
Each entry under âClassesâ and âProtocolsâ can contain âMethodsâ and âPropertiesâ arrays, in addition to the attributes described below:
- Methods:
Identified by âSelectorâ and âMethodKindâ; the MethodKind is either âInstanceâ or âClassâ.
Classes: - Name: UIViewController Methods: - Selector: "presentViewController:animated:" MethodKind: Instance âŚ- Properties:
Identified by âNameâ and âPropertyKindâ; the PropertyKind is also either âInstanceâ or âClassâ.
Classes: - Name: UIView Properties: - Name: subviews PropertyKind: Instance âŚ
Each entry under âTagsâ can contain âMethodsâ, âFieldsâ, and nested âTagsâ arrays. Methods under Tags are C++ methods identified by âNameâ (rather than âSelectorâ and âMethodKindâ as used for Objective-C methods).
- Methods (under Tags):
Identified by âNameâ.
Tags: - Name: MyClass Methods: - Name: doSomething âŚ- Fields:
Identified by âNameâ.
Tags: - Name: MyStruct Fields: - Name: value Nullability: O âŚ- Tags (nested):
Nested tags follow the same schema as top-level Tags entries.
Tags: - Name: OuterClass Tags: - Name: InnerClass âŚ
Each declaration supports the following annotations (if relevant to that declaration kind), all of which are optional:
- SwiftName:
Equivalent to
NS_SWIFT_NAME. For a method, must include the full Swift name with all arguments. Use â_â to omit an argument label.- Selector: "presentViewController:animated:" MethodKind: Instance SwiftName: "present(_:animated:)" - Class: NSBundle SwiftName: Bundle
- SwiftImportAs:
For a class, possible values are
owned(equivalent toSWIFT_SELF_CONTAINED) orreference(equivalent toSWIFT_SHARED_REFERENCE, also requires specifyingSwiftReleaseOpandSwiftRetainOp).For a method, possible values are
unsafe(equivalent toSWIFT_RETURNS_INDEPENDENT_VALUE) orcomputed_property(equivalent toSWIFT_COMPUTED_PROPERTY).Tags: - Name: OwnedStorage SwiftImportAs: owned
- SwiftRetainOp, SwiftReleaseOp:
Controls the lifetime operations of a class which uses custom reference counting. The class must be annotated as a reference type using
SwiftImportAs: reference. The values are either names of global functions, each taking a single parameter of a pointer type, orimmortalfor a type that is considered alive for the duration of the program.Tags: - Name: RefCountedStorage SwiftImportAs: reference SwiftReleaseOp: RCRelease SwiftRetainOp: RCRetain - Name: ImmortalSingleton SwiftImportAs: reference SwiftReleaseOp: immortal SwiftRetainOp: immortal
- SwiftCopyable:
Allows annotating a C++ class as non-copyable in Swift. Equivalent to
SWIFT_NONCOPYABLE, or to an explicit conformance: ~Copyable.Tags: - Name: tzdb SwiftCopyable: false
A non-copyable type can have a âdestroyâ operation, specified with SwiftDestroyOp, which will be invoked on the instance when it is no longer in use to free up resources.
Tags: - Name: WGPUAdapterInfo SwiftCopyable: false SwiftDestroyOp: wgpuAdapterInfoFreeMembers
- SwiftConformsTo:
Allows annotating a C++ class as conforming to a Swift protocol. Equivalent to
SWIFT_CONFORMS_TO_PROTOCOL. The value is a module-qualified name of a Swift protocol.Tags: - Name: vector SwiftConformsTo: Cxx.CxxSequence
- SwiftSafety:
Import a declaration as
@safeor@unsafeto Swift.Tags: - Name: UnsafeType SwiftSafety: unsafe - Name: span Methods: - Name: size SwiftSafety: safe
- Availability, AvailabilityMsg:
A value of ânonswiftâ is equivalent to
NS_SWIFT_UNAVAILABLE. A value of âavailableâ can be used in the âSwiftVersionsâ section to undo the effect of ânonswiftâ.- Selector: "dealloc" MethodKind: Instance Availability: nonswift AvailabilityMsg: "prefer 'deinit'"
- SwiftPrivate:
Equivalent to NS_REFINED_FOR_SWIFT.
- Name: CGColorEqualToColor SwiftPrivate: true
- Nullability:
Used for properties and globals. There are four options, identified by their initials:
NonnullorN(corresponding to_Nonnull)OptionalorO(corresponding to_Nullable)UnspecifiedorU(corresponding to_Null_unspecified)ScalarorS(deprecated)
Note that âNullabilityâ is overridden by âTypeâ, even in a âSwiftVersionsâ section.
Note
âNullabilityâ can also be used to describe the argument types of methods and functions, but this usage is deprecated in favor of âParametersâ (see below).
- Name: dataSource Nullability: O
- NullabilityOfRet:
Used for methods and functions. Describes the nullability of the return type.
Note that âNullabilityOfRetâ is overridden by âResultTypeâ, even in a âSwiftVersionsâ section.
Warning
Due to a compiler bug, âNullabilityOfRetâ may change nullability of the parameters as well (rdar://30544062). Avoid using it and instead use âResultTypeâ and specify the return type along with a nullability annotation (see documentation for âResultTypeâ).
- Selector: superclass MethodKind: Class NullabilityOfRet: O
- Type:
Used for properties and globals. This completely overrides the type of the declaration; it should ideally only be used for Swift backwards compatibility, when existing type information has been made more precise in a header. Prefer âNullabilityâ and other annotations when possible.
We parse the specified type as if it appeared at the location of the declaration whose type is being modified. Macros are not available and nullability must be applied explicitly (even in an
NS_ASSUME_NONNULL_BEGINsection).- Name: delegate PropertyKind: Instance Type: "id"
- ResultType:
Used for methods and functions. This completely overrides the return type; it should ideally only be used for Swift backwards compatibility, when existing type information has been made more precise in a header.
We parse the specified type as if it appeared at the location of the declaration whose type is being modified. Macros are not available and nullability must be applied explicitly (even in an
NS_ASSUME_NONNULL_BEGINsection).- Selector: "subviews" MethodKind: Instance ResultType: "NSArray * _Nonnull"
- SwiftImportAsAccessors:
Used for properties. If true, the property will be exposed in Swift as its accessor methods, rather than as a computed property using
var.- Name: currentContext PropertyKind: Class SwiftImportAsAccessors: true
- NSErrorDomain:
Used for
NSErrorcode enums. The value is the name of the associated domainNSStringconstant; an empty string ("") means the enum is a normal enum rather than an error code.- Name: MKErrorCode NSErrorDomain: MKErrorDomain
- SwiftWrapper:
Controls
NS_STRING_ENUMandNS_EXTENSIBLE_STRING_ENUM. There are three options:âstructâ (extensible)
âenumâ
ânoneâ
Note that even an âenumâ wrapper is still presented as a struct in Swift; itâs just a âmore enum-likeâ struct.
- Name: AVMediaType SwiftWrapper: none
- EnumKind:
Has the same effect as
NS_ENUMandNS_OPTIONS. There are four options:âNSEnumâ / âCFEnumâ
âNSClosedEnumâ / âCFClosedEnumâ
âNSOptionsâ / âCFOptionsâ
ânoneâ
- Name: GKPhotoSize EnumKind: none
- Parameters:
Used for methods and functions. Parameters are identified by a 0-based âPositionâ and support the âNullabilityâ, âNoEscapeâ, and âTypeâ keys.
Note
Using âParametersâ within a parameter entry to describe the parameters of a block is not implemented. Use âTypeâ on the entire parameter instead.
- Selector: "isEqual:" MethodKind: Instance Parameters: - Position: 0 Nullability: O
- NoEscape:
Used only for block parameters. Equivalent to
NS_NOESCAPE.- Name: dispatch_sync Parameters: - Position: 0 NoEscape: true
- SwiftBridge:
Used for Objective-C class types bridged to Swift value types. An empty string (ââ) means a type is not bridged. Not supported outside of Apple frameworks (the Swift side of it requires conforming to implementation-detail protocols that are subject to change).
- Name: NSIndexSet SwiftBridge: IndexSet
- SwiftReturnOwnership:
Used for methods and functions. Specifies the ownership convention for the return value when it is a foreign reference type (a type imported as
SwiftImportAs: reference). Possible values are:retainedâ the caller receives an owned reference (equivalent to__attribute__((swift_attr("returns_retained")))).unretainedâ the caller receives an unowned reference (equivalent to__attribute__((swift_attr("returns_unretained")))).
Functions: - Name: createRefCounted SwiftReturnOwnership: retained - Name: getSharedRefCounted SwiftReturnOwnership: unretained Tags: - Name: ImmortalRefType SwiftImportAs: reference Methods: - Name: createChild SwiftReturnOwnership: retained
- DesignatedInit:
Used for init methods. Equivalent to
NS_DESIGNATED_INITIALIZER.- Selector: "initWithFrame:" MethodKind: Instance DesignatedInit: true