Attributes
Attributes provide more information about a declaration or type. There are two kinds of attributes in Swift, those that apply to declarations and those that apply to types.
You specify an attribute by writing the @ symbol followed by the attribute’s name and any arguments that the attribute accepts:
@attribute name
@attribute name(attribute arguments)
Some declaration attributes accept arguments that specify more information about the attribute and how it applies to a particular declaration. These attribute arguments are enclosed in parentheses, and their format is defined by the attribute they belong to.
Declaration Attributes
You can apply a declaration attribute to declarations only. However, you can also apply the noreturn attribute to a function or method type.
autoclosureThis attribute is used to delay the evaluation of an expression by automatically wrapping that expression in a closure with no arguments. Apply this attribute to a parameter declaration for a function or method type that takes no arguments and that returns the type of the expression. Declarations with the
autoclosureattribute implynoescapeas well, except when passed the optional attribute argumentescaping. For an example of how to use theautoclosureattribute, see Autoclosures and Function Type.availableApply this attribute to any declaration to indicate the declaration’s lifecycle relative to certain platforms and operating system versions.
The
availableattribute always appears with a list of two or more comma-separated attribute arguments. These arguments begin with one of the following platform names:iOSiOSApplicationExtensionOSXOSXApplicationExtensionwatchOSwatchOSApplicationExtensiontvOStvOSApplicationExtension
You can also use an asterisk (
*) to indicate the availability of the declaration on all of the platform names listed above.The remaining arguments can appear in any order and specify additional information about the declaration’s lifecycle, including important milestones.
The
unavailableargument indicates that the declaration isn’t available on the specified platform.The
introducedargument indicates the first version of the specified platform in which the declaration was introduced. It has the following form:introduced=version number
The version number consists of one or more positive integers, separated by periods.
The
deprecatedargument indicates the first version of the specified platform in which the declaration was deprecated. It has the following form:deprecated=version number
The optional version number consists of one or more positive integers, separated by periods. Omitting the version number indicates that the declaration is currently deprecated, without giving any information about when the deprecation occurred. If you omit the version number, omit the equal sign (
=) as well.The
obsoletedargument indicates the first version of the specified platform in which the declaration was obsoleted. When a declaration is obsoleted, it’s removed from the specified platform and can no longer be used. It has the following form:obsoleted=version number
The version number consists of one or more positive integers, separated by periods.
The
messageargument is used to provide a textual message that’s displayed by the compiler when emitting a warning or error about the use of a deprecated or obsoleted declaration. It has the following form:message=message
The message consists of a string literal.
The
renamedargument is used to provide a textual message that indicates the new name for a declaration that’s been renamed. The new name is displayed by the compiler when emitting an error about the use of a renamed declaration. It has the following form:renamed=new name
The new name consists of a string literal.
You can use the
renamedargument in conjunction with theunavailableargument and a type alias declaration to indicate to clients of your code that a declaration has been renamed. For example, this is useful when the name of a declaration is changed between releases of a framework or library.// First releaseprotocolMyProtocol{// protocol definition}
// Subsequent release renames MyProtocolprotocolMyRenamedProtocol{// protocol definition}@available(*,unavailable,renamed="MyRenamedProtocol")typealiasMyProtocol=MyRenamedProtocol
You can apply multiple
availableattributes on a single declaration to specify the declaration’s availability on different platforms. The compiler uses anavailableattribute only when the attribute specifies a platform that matches the current target platform.If an
availableattribute only specifies anintroducedargument in addition to a platform name argument, the following shorthand syntax can be used instead:@available(platform name version number, *)
The shorthand syntax for
availableattributes allows for availability for multiple platforms to be expressed concisely. Although the two forms are functionally equivalent, the shorthand form is preferred whenever possible.@available(iOS8.0,OSX10.10, *)classMyClass{// class definition}
objcApply this attribute to any declaration that can be represented in Objective-C—for example, non-nested classes, protocols, nongeneric enumerations (constrained to integer raw-value types), properties and methods (including getters and setters) of classes and protocols, initializers, deinitializers, and subscripts. The
objcattribute tells the compiler that a declaration is available to use in Objective-C code.Classes marked with the
objcattribute must inherit from a class defined in Objective-C. If you apply theobjcattribute to a class or protocol, it’s implicitly applied to the Objective-C compatible members of that class or protocol. The compiler also implicitly adds theobjcattribute to a class that inherits from another class marked with theobjcattribute or a class defined in Objective-C. Protocols marked with theobjcattribute can’t inherit from protocols that aren’t.If you apply the
objcattribute to an enumeration, each enumeration case is exposed to Objective-C code as the concatenation of the enumeration name and the case name. For example, a case namedVenusin a SwiftPlanetenumeration is exposed to Objective-C code as a case namedPlanetVenus.The
objcattribute optionally accepts a single attribute argument, which consists of an identifier. Use this attribute when you want to expose a different name to Objective-C for the entity theobjcattribute applies to. You can use this argument to name classes, enumerations, enumeration cases, protocols, methods, getters, setters, and initializers. The example below exposes the getter for theenabledproperty of theExampleClassto Objective-C code asisEnabledrather than just as the name of the property itself.@objcclassExampleClass:NSObject{varenabled:Bool{@objc(isEnabled)get{// Return the appropriate value}}}
noescapeApply this attribute to a function or method declaration to indicate that a parameter will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the
noescapedeclaration attribute do not require explicit use ofself.for properties or methods. For an example of how to use thenoescapeattribute, see Nonescaping Closures.nonobjcApply this attribute to a method, property, subscript, or initializer declaration to suppress an implicit
objcattribute. Thenonobjcattribute tells the compiler to make the declaration unavailable in Objective-C code, even though it is possible to represent it in Objective-C.You use the
nonobjcattribute to resolve circularity for bridging methods in a class marked with theobjcattribute, and to allow overloading of methods and initializers in a class marked with theobjcattribute.A method marked with the
nonobjcattribute cannot override a method marked with theobjcattribute. However, a method marked with theobjcattribute can override a method marked with thenonobjcattribute. Similarly, a method marked with thenonobjcattribute cannot satisfy a protocol requirement for a method marked with the@objcattribute.noreturnApply this attribute to a function or method declaration to indicate that the corresponding type of that function or method,
T, is@noreturn T. You can mark a function or method type with this attribute to indicate that the function or method doesn’t return to its caller.You can override a function or method that is not marked with the
noreturnattribute with a function or method that is. That said, you can’t override a function or method that is marked with thenoreturnattribute with a function or method that is not. Similar rules apply when you implement a protocol method in a conforming type.NSApplicationMainApply this attribute to a class to indicate that it is the application delegate. Using this attribute is equivalent to calling the
NSApplicationMain(_:_:)function and passing this class’s name as the name of the delegate class.If you do not use this attribute, supply a
main.swiftfile with amain()function that calls theNSApplicationMain(_:_:)function. For example, if your app uses a custom subclass ofNSApplicationas its principal class, call theNSApplicationMainfunction instead of using this attribute.NSCopyingApply this attribute to a stored variable property of a class. This attribute causes the property’s setter to be synthesized with a copy of the property’s value—returned by the
copyWithZone(_:)method—instead of the value of the property itself. The type of the property must conform to theNSCopyingprotocol.The
NSCopyingattribute behaves in a way similar to the Objective-Ccopyproperty attribute.
NSManagedApply this attribute to an instance method or stored variable property of a class that inherits from
NSManagedObjectto indicate that Core Data dynamically provides its implementation at runtime, based on the associated entity description. For a property marked with theNSManagedattribute, Core Data also provides the storage at runtime.testableApply this attribute to
importdeclarations for modules compiled with testing enabled to access any entities marked with theinternalaccess level modifier as if they were declared with thepublicaccess level modifier.UIApplicationMainApply this attribute to a class to indicate that it is the application delegate. Using this attribute is equivalent to calling the
UIApplicationMainfunction and passing this class’s name as the name of the delegate class.If you do not use this attribute, supply a
main.swiftfile with amainfunction that calls theUIApplicationMain(_:_:_:)function. For example, if your app uses a custom subclass ofUIApplicationas its principal class, call theUIApplicationMain(_:_:_:)function instead of using this attribute.
warn_unused_resultApply this attribute to a method or function declaration to have the compiler emit a warning when the method or function is called without using its result.
You can use this attribute to provide a warning message about incorrect usage of a nonmutating method that has a mutating counterpart.
The
warn_unused_resultattribute optionally accepts one of the two attribute arguments below.The
messageargument is used to provide a textual warning message that’s displayed when the function or method is called, but its result isn’t used. It has the following form:message=message
The message consists of a string literal.
The
mutable_variantargument is used to provide the name of the mutating version of the method that should be used if the nonmutating method is called on a mutable value and the result isn’t used. It has the following form, where the method name consists of a string literal:mutable_variant=method name
For example, the Swift standard library provides both the mutating method
sortInPlace()and the nonmutating methodsort()to collections whose generator element conforms to theComparableprotocol. If you call thesort()method without using its result, it’s likely that you actually intended to use the mutating variant,sortInPlace()instead.
Declaration Attributes Used by Interface Builder
Interface Builder attributes are declaration attributes used by Interface Builder to synchronize with Xcode. Swift provides the following Interface Builder attributes: IBAction, IBDesignable, IBInspectable, and IBOutlet. These attributes are conceptually the same as their Objective-C counterparts.
You apply the IBOutlet and IBInspectable attributes to property declarations of a class. You apply the IBAction attribute to method declarations of a class and the IBDesignable attribute to class declarations.
Type Attributes
You can apply type attributes to types only. However, you can also apply the noreturn attribute to a function or method declaration.
conventionApply this attribute to the type of a function to indicate its calling conventions.
The
conventionattribute always appears with one of the attribute arguments below.The
swiftargument is used to indicate a Swift function reference. This is the standard calling convention for function values in Swift.The
blockargument is used to indicate an Objective-C compatible block reference. The function value is represented as a reference to the block object, which is anid-compatible Objective-C object that embeds its invocation function within the object. The invocation function uses the C calling convention.The
cargument is used to indicate a C function reference. The function value carries no context and uses the C calling convention.
A function with C function calling conventions can be used as a function with Objective-C block calling conventions, and a function with Objective-C block calling conventions can be used as a function with Swift function calling conventions. However, only nongeneric global functions, and local functions or closures that don’t capture any local variables, can be used as a function with C function calling conventions.
noreturnApply this attribute to the type of a function or method to indicate that the function or method doesn’t return to its caller. You can also mark a function or method declaration with this attribute to indicate that the corresponding type of that function or method,
T, is@noreturn T.
Grammar of an attribute
attribute
→
@attribute-nameattribute-argument-clauseopt
attribute-name → identifier
attribute-argument-clause
→
(balanced-tokensopt)
attributes → attributeattributesopt
balanced-tokens → balanced-tokenbalanced-tokensopt
balanced-token
→
(balanced-tokensopt)
balanced-token
→
[balanced-tokensopt]
balanced-token
→
{balanced-tokensopt}
balanced-token → Any identifier, keyword, literal, or operator
balanced-token
→
Any punctuation except (, ), [, ], {, or }