## Simple for statement

A simple for statement consists of an initializer, condition and an increment/decrement. In the following example, we have an variable i initialized to 0 and we check for a condition i<2 and use an increment i++. This i++ could be i+1 or i-2 and so on. It depends on your need.

```for(var i = 0; i<2; i++){
println(i)
}
```

```0
1
```

## for in with dictionaries

We can access an key value of dictionaries with for in statement. A simple example is shown below.

```var dict = ["1":"Eezy", "2":"Tutorials"]
for (key,value) in dict
{
println("\(key) : \(value)")
}
```

#### Output

```2 : Tutorials
1 : Eezy
```

## for in with arrays

We can access an array of values with for in statement. A simple example is shown below.

```var array = ["Eezy", "Tutorials"]
for value in array
{
println(value)
}
```

```Eezy
Tutorials
```

## for in with ranges

Ranges provides more power to for. You can just specify the starting and finishing values of a range. A simple example is given below. The range includes the starting and ending number

```for i in 0...3
{
println(i)
}
```

#### Output

```0
1
2
3
```

A simple example is shown below. As the name implies the block of statement for if executes if the condition is satisfied.

```let a = 20
if a == 20 {
println("\(a)")
}
```

```20
```

## if else example

A simple if else example is shown below.

```let a = 10
if a == 20 {
println("\(a)")
}
else{
println("Not 20")
}
```

#### Output

```Not 20
```

## if else ladder example

```let a = 3
if a == 1 {
println("Number is 1")
}
else if a == 2 {
println("Number is 2")
}
else if a == 3 {
println("Number is 3")
}
else{
println("UnKnown number")
}
```

#### Output

```Number is 3
```

## Optionals and if statement

```var name: String?
if let tempName = name {
println("value present")
}
else {
println("NIL")
}
```

#### Output

```NIL
```

You can see that optionals can be checked with if let syntax. Also, it copies the variable locally and helps us not making changes to the original value.

Firstly, in Swift, you no longer need to add break statement like other conventional programming languages like C. The other use of break was that if you don’t call break, it will automatically execute other cases too. For this purpose, we have fallthrough method that makes the next cases to be executed even if the current case succeeds. Let us now look at some examples.

## Simple Switch case example

```let a = 10
switch (a){
case 1:
println("Hello")
case 10:
println("World")
default:
println("Nothing")
}
```

#### Output

```World
```

Another important thing to note is that, cases should be exhaustive and hence we should add a default case to make it exhaustive. The default case should have at least one statement. The one statement could be even break if you don’t need to do any other stuff.

## Switch Ranges example

```let a = 4
switch (a){
case 1...10:
println("Hello")
default:
break
}
```

#### Output

```Hello
```

In the above example refers to range 1 to 10 with both 1 and 10 included.

## Switch with fallthrough example

```let a = 4
switch (a){
case 1...10:
println("One to ten")
fallthrough
case 5...10:
println("five to ten")
default:
break
}
```

#### Output

```One to ten
five to ten
```

As you can see in the above example, fallthrough enable all the subsequent cases to be executed. You may need to use break in case you want to break in one of the cases while using fallthrough.

## Simple tuples example

```let a = ("raj", 10)
switch (a){
case ("raj",10):
println("Raj")
case ("john",20):
println("John")
default:
break
}
```

#### Output

```Raj
```

Tuples enables us to pass multiple values and it is supported in switch case as well. In the above example, we have used a simple string and number comparison.

Swift function type makes the function to be a first class citizen. You can pass function like objects to any other function like parameters or return values.

Every function has a function type. This function type consists of the parameters and return values. A simple example for function type is shown below.

```func add(number1:Int, number2:Int)->Int{
return number1 + number2
}
```

When you run the above program, we will get the following output.

```3
```

Structures is used to represent a collection of different types. In swift, it is possible to have initializers and methods like classes. The most common difference is that class instance is passed as reference and structure is passed as copy.
Syntax

```struct structureName{
//variables and methods
}
// Structure initialization
let variableName = structureName(variable1:initialValue1,...,variablen:initialValuen)
```

Example

```struct Student{
var name:String
var rollNo:String
func desc()->String{
return "The name of student with roll number\(rollNo) is \(name)"
}
}
```

Protocols provides ability for us to define properties and methods that a task should conform to. For example, let us consider we have a Driving protocol. It may have methods and properties like brake and speed that conforming Car class should implement.

Syntax

```protocol protocolName{
//methods and properties
}
```

Example

```protocol DrivingProtocol{
var speed: Int { get }
func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
func brake(){
}
}
```

Objective C Compatible Protocol Syntax

```@objc protocol protocolName{
//methods and properties
optional
//optional methods
}
```

Example

```@objc protocol DrivingProtocol{
var speed: Int { get }
optional
func brake()
}
//Implemetation of protocol in class car
class Car:Vehicle,DrivingProtocol{
//Optional to add brake function
}
```

In this section, we will see the variable valid tokens that forms the basic structure of the swift program also called the lexical structure. The valid tokens include,

Comments are those statements intended to add some additional information to fellow developers. These statements are ignored and skipped by the compiler. We have two types of comments namely single line comments and multiline (or block) comments as shown below in example.

```// Single line comment
/* Multi line (or block) comment - can use
multiple lines */
```

## Whitespace

Whitespace is used to separate different tokens and also add readability to code. Whitespace characters for readability especially used in binary operations are ignored and skipped by the compiler. An example shown below in example.

```var a = 19
var sum = a + 20
```

You can find whitespace characters found in the above example. The space between var and a are mandatory as they are two different tokens. But the space between a and =, and the space between = and 19 are just for readability. Similar whitespace characters are used in sum = a + 20 only for readability.

## Identifiers

Identifiers can contain alphabets, numbers and combining unicode characters. Identifiers can begin with an upper case or lower case letter A through Z, an underscore (_), a noncombining alphanumeric unicode character in the basic multilingual plane, or a character outside the basic multilingual plane that isn’t in a private use area as per apple swift language guide. Due to support of unicode characters, its now possible to name variables in your native languages across the world.

As in all programming languages, you cannot use keywords for identifiers. But, if you still want to use it, keyword can be used by adding a backtick(`) before and after it. But x and `x` are not different. Examples of valid identifiers are shown in following example.

```_variable `class` name number123

переменная 変数
```

## Keywords

The list of keywords in swift are listed below.

 class deinit enum extension func import init let protocol static struct subscript typealias var break continue default do else fallthrough if in for return switch where while as dynamicType is new super self Self Type __COLUMN__ __FILE__ __FUNCTION__ __LINE__ associativity didSet get infix inout left mutating none nonmutating override precedence prefix right set unowned unowned(safe) unowned(unsafe) weak willSet

## Literals

Literals can be any three of the following.

• Integer literals
• Floating point literals
• String literals

These are nothing but values we assign to variables. Examples of the above literals are given below.

```// Integer literal 10
var a = 10
// Floating point literal 10.4
var b = 10.4
var c = "Hello"
```

### Integer Literals

Integer literal can be represented in decimal, binary, octal and hexadecimal forms. An example for representing a integer decimal number 20 in different forms is shown below.

```//Decimal integer literal 20
var a = 10
//Binary integer literal 20
var b = 00010100b
//Hexadecimal integer literal 20
var c = 14x
//Octal integer literal 20
var d = 24o
```

One of the new features available in swift is that you can use underscore(_) between digits for readability as shown below. Similarly, leading zeros will be ignored by compiler.

```var a = 100_000_000
```

### Floating point Literals

Floating point numbers can be simple decimal numbers, exponential numbers both decimal and hexadecimal floating point numbers. An simple example is shown below.

```//Simple floating point number
var a = 10.5
//Exponent floating point number for 1050
var b = 10.5e2
//Exponent floating point number for 0.1050
var c = 10.5e-2
//Hexa decimal exponent floating point number for 40
var d = 0xAp2
//Hexa decimal exponent floating point number for 2.5
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"
```

### Escape sequences

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

## Operators

There are different operators supported in swift which includes + ,- ,* , /, %, ^, &, &&,| , ||, ++, –, ~, < ,> ,. ,-> ,!. The list of operators are explained in swift- operators tutorial.

© 2020 Eezy Tutorials