Swift Variables and Constants
5 (1)

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

Any meaningful program should contain stores to save data, swift distinguishes between constant and variable pieces of data with let and var keywords, for example, say you have a customer object, their birthdate is a constant, but their balance is a variable, if you declare data as a constant, the compiler will not allow you to have it changed later, even at compile time, this is not only for safety, but constants are generally faster to work with by the processor.

class Customer {
	let id = 22034
	let birthdate = "11/11/2011"
	var balance = 109.3
}

Constants cannot change after you run your app, they prevent accidental breakage of a value that should not change.

Swift Style Guides (a brief look)
5 (1)

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

You most probably was working on an open source project, and must have noticed projects are usually organized and consistent 🧐, this is due to following a code style, and you must have noticed that some projects are messy, ugly and inconsistent 🤮.

There are different Swift Code Styles, one by Apple, Google, Ray Wenderlich, Linkedin and AirBNB, and others, preferring a code style over another is subjective, I recommend inspecting different styles and adopt one according to the project needs.

Developers spend time reading code, more than writing new code 😌, this alone justifies having a consistent clean coding style, this is an investment you do for yourself as a developer, and for your colleagues 😇, regular indentation, proper spelling, .. etc does not make your task take longer, in the contrary, it saves you big load of time in the future, and improves readability and maintainability.

There is an official API Design guidelines, it covers naming conventions, but is not comprehensive enough.

Another guideline can be found here, by Nikita Lazarev-Zubov, it looks like she has preservations on some guidelines too, I highly recommend going through these guidelines and inspecting yourself.


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)