In Swift, sometimes, keywords are plain keywords, and some others start with an @
.
For instance, weak
, unowned
, inout
, class
are plain. But @final
, @lazy
start with @
.
Sometimes, we even have both! prefix
and @prefix
, infix
and @infix
for instance.
It is not entirely an Objective-C inheritance since we have @class
and not class
in Objective-C. I could understand why we have class
and not @class
in Swift, but since we have @final
or @lazy
, I would have thought that it should be @weak
and not weak
.
Why this choice? Is there a kind of intuitive way that should tell: "hey, it is logical that this keyword starts with @
?
Even if I think with a preprocessor perspective in mind, it is not obvious that @
would call a kind of specific preprocessor before compilation (e.g. @final
is not really a kind of preprocessor directive).
Swift keywords are the words reserved for a purpose. They cannot be used for variable names constants or any other identifiers. There are four types of keywords in Swift based on the location of their usage in a swift program.
You use where in Swift to filter things, kinda like a conditional. In various places throughout Swift, the “where” clause provides a constraint and a clear indicator of the data or types you want to work with. What's so special about where – as you'll soon see – is its flexible syntax.
The some keyword was introduced in Swift 5.1 and is used to define an Opaque Type.
@
-prefixed items in Swift are not keywords, these are attributes.
Apple's book on Swift says that
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.
Some attributes (such as @objc(isEnabled)
) accept parameters.
The main difference between attributes and keywords is that keywords tell the compiler what you are defining (a class, a method, a property, a variable, and so on), while attributes tell the compiler in what contexts you intend to use that definition. For example, you would use a func
keyword to tell the compiler that you are defining a function, and decorate that function with an @infix
attribute to tell the compiler that you plan to use that function as an infix operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With