Have you ever ever heard about Swift language attributes? On this article I am attempting to assemble all of the @ annotations and their meanings.
Swift
Have you ever ever heard about Swift language attributes? On this article I am attempting to assemble all of the @ annotations and their meanings.
Public attributes
Public Swift language attributes are marked with the @ image, they’re (kind of) properly documented and prepared to be used. Right here is the whole listing of all the general public Swift language attributes. Most of them will appear very acquainted… 😉
@IBOutlet
In case you mark a property with the @IBOutlet attribute, the Interface Builder (IB) will acknowledge that variable and you’ll join your supply together with your visuals via the offered “outlet” mechanism.
@IBOutlet weak var textLabel: UILabel!
@IBAction
Equally, @IBAction is an attribute that makes attainable connecting actions despatched from Interface Builder. So the marked technique will instantly obtain the occasion fired up by the person interface. 🔥
@IBaction func buttonTouchedAction(_ sender: UIButton) {}
@IBInspectable, @GKInspectable
Marking an NSCodable
property with the @IBInspectable attribute will make it simply editable from the Interface Builder’s inspector panel. Utilizing @GKInspectable has the identical conduct as @IBInspectable, however the property shall be uncovered for the SpriteKit editor UI as an alternative of IB. 🎮
@IBInspectable var borderColor: UIColor = .black
@GKInspectable var mass: Float = 1.21
@IBDesignable
When utilized to a UIView
or NSView
subclass, the @IBDesignable attribute lets Interface Builder know that it ought to show the precise view hierarchy. So principally something that you just draw inside your view shall be rendered into the IB canvas.
@IBDesignable class MyCustomView: UIView { }
@UIApplicationMain, @NSApplicationMain
With this attribute you possibly can mark a category as the applying’s delegate. Often that is already there in each AppDelegate.swift
file that you will ever create, nevertheless you possibly can present a most important.swift
file and name the [UI|NS]ApplicationMain
technique by hand. #pleasedontdoit 😅
@obtainable
With the @obtainable attribute you possibly can mark varieties obtainable, deprecated, unavailable, and so forth. for particular platforms. I am not going into the main points there are some nice posts about find out how to use the attribute with availability checkings in Swift.
@obtainable(swift 4.1)
@obtainable(iOS 11, *)
func avaialbleMethod() { }
@NSCopying
You’ll be able to mark a property with this attribute to make a duplicate of it as an alternative of the worth of the property iself. Clearly this may be actually useful if you copy reference varieties.
class Instance: NSOBject {
@NSCopying var objectToCopy: NSObject
}
@NSManaged
If you’re utilizing Core Knowledge entities (normally NSManagedObject
subclasses), you possibly can mark saved variables or occasion strategies as @NSManaged to point that the Core Knowledge framework will dynamically present the implementation at runtime.
class Particular person: NSManagedObject {
@NSManaged var identify: NSString
}
@objcMembers
It is principally a comfort attribute for marking a number of attributes obtainable for Goal-C. It is legacy stuff for Goal-C dinosaurs, with efficiency caveats. 🦕
@objcMembers class Particular person {
var firstName: String?
var lastName: String?
}
@escaping
You’ll be able to mark closure parameters as @escaping, if you wish to point out that the worth may be saved for later execution, so in different phrases the worth is allowed to survive the lifetime of the decision. 💀
var completionHandlers: [() -> Void] = []
func add(_ completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}
@discardableResult
By default the compiler raises a warning when a operate returns with one thing, however that returned worth isn’t used. You’ll be able to suppress the warning by marking the return worth discardable with this Swift language attribute. ⚠️
@discardableResult func logAdd(_ a: Int, _ b: Int) -> Int {
let c = a + b
print(c)
return c
}
logAdd(1, 2)
@autoclosure
This attribute can magically flip a operate with a closure parameter that has no arguments, however a return sort, right into a operate with a parameter sort of that unique closure return sort, so you possibly can name it way more simple. 🤓
func log(_ closure: @autoclosure () -> String) {
print(closure())
}
log("b")
@testable
In case you mark an imported module with the @testable attribute all the inner access-level entities shall be seen (obtainable) for testing functions. 👍
@testable import CoreKit
@objc
This attribute tells the compiler {that a} declaration is accessible to make use of in Goal-C code. Optionally you possibly can present a single identifier that’ll be the identify of the Goal-C illustration of the unique entity. 🦖
@objc(LegacyClass)
class ExampleClass: NSObject {
@objc personal var retailer: Bool = false
@objc var enabled: Bool {
@objc(isEnabled) get {
return self.retailer
}
@objc(setEnabled:) set {
self.retailer = newValue
}
}
@objc(setLegacyEnabled:)
func set(enabled: Bool) {
self.enabled = enabled
}
}
@nonobjc
Use this attribute to supress an implicit objc attribute. The @nonobjc attribute tells the compiler to make the declaration unavailable in Goal-C code, regardless that it’s attainable to signify it in Goal-C. 😎
@nonobjc static let take a look at = "take a look at"
@conference
This attribute point out operate calling conventions. It might probably have one parameter which signifies Swift operate reference (swift), Goal-C appropriate block reference (block) or C operate reference (c).
func a(a: Int) -> Int {
return a
}
let exampleSwift: @conference(swift) (Int) -> Int = a
exampleSwift(10)
Personal attributes
Personal Swift language attributes ought to solely be utilized by the creators of the language, or hardcore builders. They normally present additional (compiler) performance that’s nonetheless work in progress, so please be very cautious… 😳
Please don’t use personal attributes in manufacturing code, until you actually know what you might be doing!!! 😅
@_exported
If you wish to import an exterior module in your complete module you should utilize the @_exported key phrase earlier than your import. From now the imported module shall be obtainable all over the place. Bear in mind PCH recordsdata? 🙃
@_exported import UIKit
@inline
With the @inline attribute you explicitly inform the compiler the operate inlining conduct. For instance if a operate is sufficiently small or it is solely getting referred to as a couple of instances the compiler is possibly going to inline it, until you disallow it explicitly.
@inline(by no means) func a() -> Int {
return 1
}
@inline(__always) func b() -> Int {
return 2
}
@_inlineable public func c() {
print("c")
}
c()
@inlinable is the long run (@_inlineable) by Marcin Krzyzanowskim 👏
@results
The @results attribute describes how a operate impacts “the state of the world”. Extra virtually how the optimizer can modify this system based mostly on data that’s offered by the attribute.
You will discover the corresponding docs right here.
@results(readonly) func foo() { }
@_transparent
Principally you possibly can pressure inlining with the @_transparent attribute, however please learn the unofficial documentation for more information.
@_transparent
func instance() {
print("instance")
}
@_specialize
With the @_specialize Swift attribute you may give hints for the compiler by itemizing concrete varieties for the generic signature. Extra detailed docs are right here.
struct S<T> {
var x: T
@_specialize(the place T == Int, U == Float)
mutating func exchangeSecond<U>(_ u: U, _ t: T) -> (U, T) {
x = t
return (u, x)
}
}
@_semantics
The Swift optimizer can detect code in the usual library whether it is marked with particular attributes @_semantics, that identifies the capabilities.
You’ll be able to examine semantics right here and right here, or inside this concurrency proposal.
@_semantics("array.depend")
func getCount() -> Int {
return _buffer.depend
}
@silgenname
This attribute specifies the identify {that a} declaration could have at hyperlink time.
You’ll be able to examine it contained in the Normal Librery Programmers Handbook.
@_silgen_name("_destroyTLS")
inner func _destroyTLS(_ ptr: UnsafeMutableRawPointer?) {
}
@_cdecl
Swift compiler comes with a built-in libFuzzer integration, which you should utilize with the assistance of the @_cdecl annotation. You’ll be able to be taught extra about libFuzzer right here.
@_cdecl("LLVMFuzzerTestOneInput") public func fuzzMe(Knowledge: UnsafePointer<CChar>, Dimension: CInt) -> CInt{
}
}
Unavailable, undocumented, unknown
As you possibly can see that is already fairly a listing, however there may be much more. Contained in the official Swift repository yow will discover the attr exams. In case you want extra data in regards to the remaining Swift annotations you possibly can go instantly there and verify the supply code feedback. In case you may assist me writing in regards to the leftovers, please drop me a couple of traces, I would actually recognize any assist. 😉👍
- @requiresstoredproperty_inits
- @warnunqualifiedaccess
- @fixedlayout
- @_versioned
- @showin_interface
- @_alignment
- @objcnonlazy_realization
- @_frozen
- @_optimize(none|pace|measurement)
- @_weakLinked
- @consuming
- @_restatedObjCConformance
- @_staticInitializeObjCMetadata
- @setterAccess
- @rawdoccomment
- @objc_bridged
- @noescape -> eliminated, see @escaping
- @noreturn -> eliminated, see By no means sort
- @downgradeexhaustivity_check -> no impact on change case anymore?
- @_implements(…) – @implements(Equatable, ==(:_:))
- @swiftnativeobjcruntime_base(class)
The @_implements attribute, which treats a decl because the implementation for some named protocol requirement (however in any other case not-visible by that identify).
This attribute signifies a category that needs to be handled semantically as a local Swift root class, however which inherits a particular Goal-C class at runtime. For many courses that is the runtime’s “SwiftObject” root class. The compiler doesn’t have to know in regards to the class; it is the construct system’s duty to hyperlink towards the ObjC code that implements the basis class, and the ObjC implementation’s duty to make sure cases start with a Swift-refcounting-compatible object header and override all the required NSObject refcounting strategies.
This permits us to subclass an Goal-C class and use the quick Swift reminiscence allocator.
If you wish to add some notes about these attributes, please contact me on twitter.