Swift Sintax Summary
This is a short summary of Swift sintax.If you are not familiar with programming, I recommend you to study some basic concept of programming(Object Oriented to be precise) before looking at this guide.
I will introduce only Swift sintax, since before reading these tutorials, you should have acquired all the programming basics: if you have experience with C for example, you will face no troubles reading these lectures.The more you know how a computer architecture works, how memory works, stack, heap, pointers, CPU etc… the better it is, beacause you know what’s gonna happen when you run a piece of code.
VARIABLES AND CONSTANT
As you know, in order to have better performance, it is useful to make a distinction between constants and variables. No ; required in Swift.
let veichleName = "Ford RANGER" //constant
var km = 1000 //variable
In order to get a variable inside a string you should use the following notation:
var age = 20
print("This is a String.The age variable's value is:\(age)")
\(VARIABLE NAME) to get the value of a variable, inside a string.
Look also at the convention used for variable’s name: the Cammel Case notation: to be more readable, programmers use to write variable names with the first letters lowercase and the the first letter of the second word inside the variable name with capital letter.
So if you have a variable that identify the age of a student, studentAge is a good readable name for that variable.
PARAMETERS AND FUNCTIONS
As you can see it is really simple: all the function parameters have a type and a name.These are called named parameters.When you call the function, you specify the name of the parameter and then you pass the value(f.e. n1:23 , n1 is the name of the parameter and 23 the value it will have).
I assume you already know the functions lifecycle, local and global environment…
Calling a parameter with a long name can be useful in order to remember what that parameter is but at the same time is annoying when writing inside the function to have a long name.So programmers use Etiquette(I will call it tag,probably is not the appropriate term): the tag will appear when calling the function(so that who use the function know what he’s gonna pass to it),but inside the function code, you will call the parameter with its short name:
Those are named parameters.
There are also positional parameters:you don’t need to use a name to identify the parameters when calling the function,but you just pass them using the position in which they are declared(just like C).
ARRAY AND FOR CYCLE
You know what an array is, so let’s see the sintax and how we can iterate its elements.
ENUMS
enum is a high-level structure that allows you to use a safe sintax in order to describe elements that have some kind of relation.
Sintax:
enum regioni{
case sardegna
case campagna
case trentino
}
or inline:
enum regioni{
case sardegna,campagna,trentino
}
enum allows you to define a new data type that can have only the value inside of its definition.
Use:
let regione = regioni.sardegna
//here's how to iterate through its values
switch regione{
case .sardegna:
print("Your region is Sardegna")
case .trentino:
print("Your region is Trentino Alto Adige")
default:
print("the constant regione is empty!Please select a region.")
}
You can also assign a value to each field.For example, you can number the region of Italy starting from 1(indicating the first from South Italy) to 21(indicating the last,in North direction).
enum RegioneItalia: Int {
case sicilia = 1
case calabria = 2
case basilicata = 3
case puglia = 4
//ecc
}
In order to access to that number you have to use the property .rawValue:
var sicilia = RegioneItalia.sicilia
print(sicilia.rawValue) // it will print "1"
CLASS AND STRUCTURE
Both classes and structures are considered objects and this is what they have in common:
- Both of them can define properties in order to store values
- Both of them can have methods(functions) that works with other objects
- Can be extended through extension
- They can implement protocols
- Having a class builder(init)
So here’s the difference between a class and a structure:
Identity operators:
==
operator checks if their instance values are equal, "equal to"
===
operator checks if the references point the same instance, "identical to"
Let’s suppose we have a class called Person which have “ssn” and “name” as parameters:
let person1 = Person(ssn: 5, name: "Bob")
let person2 = Person(ssn: 5, name: "Bob")
if person1 == person2 {
print("the two instances are equal!")
}
if person1 === person2 {
print("the two instances are not identical!")
}
Example of a class:
class Animale {
var nome: String!
}
class Mucca: Animale {}
class Maiale: Animale {}
var fattoria: [Animale] = [Mucca(), Mucca(), Maiale()]
class UnaClasse {
init() {
// object builder
print("creating the object...")
}
deinit {
// distruzione dell'oggetto
print("deallocating the object")
}
}
var unaVar: UnaClasse? = UnaClasse.init()
unaVar = nil // call to deinit
nil is the equivalent of NULL.
… OPERATOR
it is like a range: in human language 0…9 it is like to say “from 0 to 9”.So in the first line, if destination is between 0 and 9 it will print “Your destination is close”.
This operator can be used anywhere.
SHORT IF
PROTOCOL
As suggested by the name, protocol is something that obblige you to follow certain rules.
It is a group of attributes and properties that a class must have,otherwise compilator will return us an error!
EXTENSION
With extention you can extend a class funtionalities that you or someone else have created.When you are building an app, you will use many classes created by other developers(Apple Developers in most of the cases), so you will be able to extend their functionalities.
GET AND SET METHODS
get and set are 2 methods for initializing variables.We will see 2 examples.
set is used to change the value, while get is used for initializing.
Get is executed automatically whenever you try to get the value of the variable.
OPTIONALS
Optionals are variables that we don’t want to initialize immediately.Until they’re not initialized, they will hold nil.
DO-WHILE
Is the same of other languages, but it is called repeat-while:
repeat{
//CODE
//...
} while CONDITION
COLLECTION TYPES
Swift has three collection types: arrays, which store an ordered list of values; dictionaries, which store an unordered list of key-value pairs; and sets, which store an unordered list of values.
//=============DICTIONARY===============
var contactList = ["rachel": "+3922384783", "jack": "+0223456789"]
//here's how to iterate a dictionary
for (name, contactNumber) in contactList {
print("\(name) : \(contactNumber)")
}
methods like add, isEmpty etc… are working also on dictionaries.
PASS AN ARRAY TO A FUNCTION
GUARD STATEMENT
It is a command that goes inside a function in an expression, so a variable or a constant.If it returns a false, the program exit immediately from the function.
func FunctionName (){
//...
guard CONDITION else{
//INSTRUCTION TO EXECUTE IF CONDITION IS FALSE
}//...INSTRUCTIONS IF IT IS TRUE
//...
}
Guard can be used in 2 cases:
1-Control during variable initialization
so, in this case, if errors occours(like assigning a wrong type to the variable), instead of bloking the entire execution and return a run-time error, it will be executed a special block(else) that avoid the program to crash and to do something different to try to solve the exeption.
2-Simple condition control
CLOSURES
A closure is like a function that has no name,but it’s declared inside curly braces{} and it is assigned to a variable or a constant.
You'll now write a closure that applies a calculation on each element of an array of numbers. Add the following code to your playground and click the Play/Stop button to run it:
var numbersArray = [2, 4, 6, 7]
let myClosure = { (number: Int) -> Int in
let result = number * number
return result
}
let mappedNumbers = numbersArray.map(myClosure)
This assigns a closure that calculates a number's power of two to myClosure. The map() function then applies this closure to every element in numbersArray. Each element is multiplied by itself, and [4, 16, 36, 49] appears in the Results area.
ERROR HANDLING
You can use a try-catch or do-catch block.
do{
//instruction
}
catch{
//error instructions...
}