Swift Reserved Keywords, with brief explanations.
5 (2)

Click to rate this post!
[Total: 2 Average: 5]

A reserved word is a word that cannot be used as an identifier, this is a syntactic definition, as mentioned before in Swift Lexical Structure, all lists below are written alphabetically.

  • Keywords used in declarations: 
Reserved WordDetails
associatedtypeAssociated types are a powerful way of making protocols generic, it gives a placeholder name to a type that’s used as part of the protocol.
classOne of swift’s general purpose, flexible constructs
also see struct
deinitA method that gets automatically called when an object is freed up from memory by ARC.
enumEnums let’s you define a custom kind of value in Swift, with predefined possible values.
extensionExtensions add new functionality to an existing class, structure, enumeration, or protocol type.
fileprivateOne of swift’s access modifiers.
funcUsed for creating functions.
importA declaration used for importing modules and submodules
initas per swift documentation, “Initialization is the process of preparing an instance of a class, structure, or enumeration for use.”
inoutinout allows parameters to be changed outside of the function scope.
internalOne of swift’s access modifiers.
letA keyword used for declaring a constant
openOne of swift’s access modifiers.
operatorA special symbol/ phrase that you use to check, change, or combine values.
privateOne of swift’s access modifiers.
precedencegroupdefining precedence groups to use for our custom operators.
protocolas per swift’s official documentation “A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.”
publicOne of swift’s access modifiers.
rethrowsrethrows keyword is used with function that accepts a throwing function as a parameter.
staticdefines a static scope.
structcomplex value-types.
subscriptSubscripts allow you to write shortcuts to elements from collections, Sequences in classes, structures and enumerations.
typealiasDefines an alias for an existing type.
varA keyword used for declaring a variable.
  • Keywords used in statements:
Reserved WordDetails
breakOne of the control transfer statements, ends execution of a loop, an if statement, or a switch statement.
caseUsed for pattern testing.
catchUsed for handling any potential errors caused by a function that throws.
continueOne of the control transfer statements, ends execution of the current iteration of a loop statement but does not stop execution of the loop statement.
defaultUsed for default cases in switch.
deferUsed for making a block to execute just before a function exits.
doUsed for creating do blocks, for example (do-while, do-catch)
elseUsed for executing a block when a condition is not satisfied.
fallthroughOne of the control transfer statements
forUsed for iterating over a sequence.
guardUsed in control transfer statement and optional unwrapping.
ifUsed for condition evaluation.
inIn is a keyword defined in the Swift closure syntax as a separator between the function type and the function body in a closure, and used in checking if an object is in a sequence.
repeatA control flow statement, similar to while loop
returnOne of the control transfer statements
throwUsed for throwing an error in a function that throws.
switchA switch statement considers a value and compares it against several possible matching patterns.
whereUsed to filter out values, in statements like switch, for, protocol extension, first, contains, initializers.
whileA control flow statement, it performs a set of statements until a condition becomes false
  • Keywords used in expressions and types:
Reserved WordDetails
AnyAny can represent an instance of any type at all, including function types.
asUsed for type casting.
catchUsed in error handling, when an error is thrown, it’s matched against the catch clauses.
falseA literal used to express booleans.
isUsed to check whether an object is of a certain class type
nilA valueless state that could be assigned to optionals.
rethrowsallows forwarding a thrown error by a given function parameter
self“self” refers to the current object within a class or struct.
SelfRefers to a type – usually the current type in the current context.
supersuper is used to call up to your superclass.
throwUsed for throwing an error in a function that throws.
throwsTo mark a function throwing.
trueA literal used to express booleans.
tryThe try keyword is used to indicate that a method can throw an error. To catch and handle an error, the throwing method call needs to be wrapped in a do-catch statement.
  • Keywords used in patterns: 
Reserved Word
_
.
  • Keywords that begin with a number sign (#), literals expressions: 
Reserved WordDetails
#availableUsed to determine the availability of APIs at runtime
#colorLiteralUsed to make the XCode IDE to display a color swatch 🟥
#columncolumn number of the line where it is being run.
#dsohandle
#elseifLiteral conditional statement
#elseLiteral else statement.
#endifLiteral marker for closing an a literal if statement
#errorCreates a red compiler error & prevents code from compiling
#fileIDGenerates concise file string in all language modes.
#fileLiteralUsed to make the XCode IDE link to a local file.
#filePathOutputs the file path of in which code is being run.
#fileOutputs the name of the file in which code is being run.
#functionOutputs the name of the function where code belongs.
#ifLiteral if statement.
#imageLiteralUsed to make the XCode IDE to display an image.
#keyPath
#lineline number where it is being run.
#selector
#sourceLocation
#warningwill cause Xcode to display a warning with the given message. 
  • Keywords reserved in particular contexts: 
Reserved WordDetails
associativitydefines how operators of the same precedence are grouped together.
convenienceConvenience modifier placed before the init keyword.
didSetA property observer
dynamicA declaration modifier used to make use of Objective-C’s dynamism.
finalOne of Swift’s access modifiers.
getUsed when getting a computed property.
indirectUsed for recursive Enums
infixUsed when creating custom operators.
lazyUsed for just-in-time calculation.
leftUsed to specify the associativity of a custom operator
mutatingFunctions marked as mutating can change any property within its enclosing value
noneUsed to specify the associativity of a custom operator
nonmutating
optional
overrideUsed for overriding child classes.
postfixUsed in creating custom functions, it’s mathematical notation in which operators follow operands.
precedenceOperator precedence is a set of rules that determine which operator is executed before another.
prefixUsed in creating custom functions, it’s mathematical notation in which operators follow operands.
ProtocolA protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
requiredRequired keyword means that inheriting classes must provide an implementation of the method.
rightUsed to specify the associativity of a custom operator
setUsed when getting a computed property.
somedenotes an opaque type.
TypeA metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types.
unownedA reference type, used for memory management.
weakA reference type, used for memory management.
willSetA property observer
  • Outside the context in which they appear in the grammar, they can be used as identifiers.

The following tokens are reserved as punctuation and can’t be used as custom operators: 

(){} []
 .,:
;=@
#& (as a prefix operator)->
`?! (as a postfix operator)

Swift Lexical Structure
5 (2)

Click to rate this post!
[Total: 2 Average: 5]

Swift lexical structure, consists of valid tokens (lowest-level building blocks) that form the structure of any swift program, these tokens describe the rest of whole swift language…

A token consists of an identifier, keyword, punctuation, literal, or operator.

1) Identifiers:
An example of an identifier is a variable name, for example here “pet” is an identifier.

let pet = "Happy Dinosaur 🦖";

Identifiers support unicode characters, you can name you variable in you native language, and as in other programming languages, you cannot use keywords as identifiers, this is still possible if you surrounding a keyword with back-ticks,

var `var` = "var"

examples of unicode identifiers are

var _latitude = 32.0;
var アップル = "apple"
;

2) Keywords:
The list of basic keywords in swift are listed below, see (Swift Reserved Keywords) for comprehensive list and details.

classdeinitenum
extensionfuncimport
initletprotocol
staticstructsubscript
typealiasvarbreak
continuedefaultdo
elsefallthroughif
inforreturn
switchwherewhile
asdynamicTypeis
newsuperself
SelfType__COLUMN__
__FILE____FUNCTION____LINE__
associativitydidSetget
infixinoutleft
mutatingnonenonmutating
overrideprecedenceprefix
rightsetunowned
unowned(safe)unowned(unsafe)weak
willSet

3) Literals:
literals fall into 3 categories, integer, floating point, and string literals

Integer Literals
var a = 10

//Binary
var b = 00010100b


//Hexadecimal
var c = 14x


//Octal
var d = 24o


leading zeros will be ignored by the compiler, and the use of underscores is possible to increase readability.

var a = 100_000_000

Floating Point Literals
//Simple floating point number
var a = 10.7


//Exponent floating point number
var b = 10.6e2

var c = 10.1e-2
//Exponent floating point number

//Hexa decimal exponent
var d = 0xAp2


//Hexa decimal exponent
var d = 0xAp-2


String Literals

String literals are characters are enclosed within double quotes. Strings can contain escape sequences to represent characters like qoutes. Example for string literal is shown below.

var a = “test”
var a = “Hello\nWorld”

\0 Null Character
\ Backslash
\t Horizontal Tab
\n New line
\r Carriage Return
\” Double Quote
\’ Single Quote


4) Operators:
There are different operators supported in swift which includes
+ : Addition
– : Subtraction
* : Multiplication
/ : Division
% : Remainder
^ : Exponent
& : Bitwise And
&& : Logical And
| : Bitwise Or
|| : Logical Or
++ : Increment Operator
– : Minus
~ : Bitwise Not
< : Less Than
> : Greater Than
… etc.

Keep in mind, as in Swift’s official documentation, this is a list of reserved punctuation and can’t be used as custom operators:
(){}[].,:;=@#& (as a prefix operator), ->`?, and ! (as a postfix operator)”

Swift Whitespace:
White spaces are used to separate tokens and to distinguish prefixes, otherwise it’s normally omitted by the compiler.

Swift Comments:
these are statements that are ignored by the compiler, and meant for documentation purposes of our code, they could be either one-line or multi-line.

// This is a single line comment

/* Multi line (block) comment - can have
more than one line! */



Swift Pros over Obj-C
5 (1)

Click to rate this post!
[Total: 1 Average: 5]

Obj-C development dates back to 1980s, Swift came with a lot of significant improvements in clarity, performance, safety, and more.

1- Swift is easier to read and maintain

Swift drops legacy conventions, using semicolons to end lines are not needed, also parenthesis are not needed around (conditional expressions), no bracket hell needed for method calls, two-file requirement is dropped by swift, the LLVM compiler can figure out dependencies automatically…

for example, swift adopts modern programming language features like concatenation of two strings together with a “+” operator, along with string interpolation which makes things easier and safer, instead of memorizing special tokens  (%s%d%@), that can be a source of crashes!

2- Swift is more safe, and have better memory management

in Obj-C nothing happens if you call a method with a nil pointer variable, not crashing may look like a benefit, but actually this is a source of bugs and unexpected behavior, optional types in swift solves this problem, this means any bug will be fixed sooner or avoided at all in swift code.

In contrast to swift, in Objective-C, ARC is not available for procedural C and other APIs like CoreGraphcis, swift saves the developer brain power for better things, like writing the app’s main logic, instead of handling memory management.

3- Swift is faster, and is less prone to name collisions

A lot of people made benchmarks, concluding swift being faster and more performant than Obj-C.

a benchmark made by apple.

Obj-C lacked name-spacing, to overcome this issue, a common practice was using a few letters as a prefix, for example NSArray (after NextStep, a company by Steve Jobs), or NSString, … etc.

In swift, namespaces are based on the target that a file relies in, for example, both apple frameworks and google frameworks can have a file called Authentication.swift

4- Swift Supports Dynamic libraries

Obj-C only support static libraries, this is a big downside, swift support dynamic libraries, that can be loaded into the app’s memory directly, this reduces the app total size, and reduces the load time of (on demand) new content.

5- Swift is open-source and has bigger community
Swift has a big community that are actively contributing, hence open-source, it started running in other environments like linux. for example of swift outside of the apple ecosystem, see vapor,  a web framework for Swift.

The Swift language is developed in the open, and all technical or administrative topics about the language or community processes should be directed to the Swift public forums. Public conversations are encouraged, and active developers of the Swift language should monitor the relevant forum categories.

Swift.org