Learn Swift with me
Tags: swift, programming, tutorial, beginners
Published: 2022-03-11 08:48:46

Swift is a programming language for developing apps for IOS and Mac OS, and it is destined to become the foremost computer language in the mobile and desktop space.Made to replace Objective-C.Swift code can communicate with obj-c but provides a better readable syntax.

**Objective-C Hello world:**
```
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   NSLog (@"hello world");
   [pool drain];
   return 0;
}
```
**Swift Hello World:**
```
var str = "Hello, World!"
print(str)
```

Pretty easy compared to obj-c right?
Let's get into it:

##**Installing:**
You need swift installed in your machine to run swift code.
You can download it from: [here](https://www.swift.org/download/)

##**Swift Variables, Constants and Literals**
Variables:
A variable is a container to hold data.
In swift, we use the `var` keyword to declare a variable and it is dynamic that means you do not need to assign datatypes but you can if you want to.
```
var name = "Rick"
print(name)
//output: rick
```
**Assign Datatypes to Variables**
```
var siteName: String
siteName = "dev.to"
print(siteName) 
```
You can assign datatypes by `: type`.For example: `number: Int` `name: String` .

Variables names must start with either a letter, an underscore `_`, or the dollar sign `$`. For example,
```
// valid
var a = "hello"
var _a = "hello"
var $a = "hello"
//invalid
var 1a = "hello"
```

Swift is case-sensitive. So A and a are different variables. For example,
```
var A = 5 
var a = 55
print(A) // 5
print(a) // 55
```
Swift Constants
A constant is a special type of variable whose value cannot be changed. For example,
```
let x = 80
x = 60
print(x)
//error
main.swift:4:1: error: cannot assign to value: 'x' is a 'let' constant
```
Avoid using reserved keywords[String, for etc] for variable names

Swift Literals
Literals are representations of fixed values in a program. They can be numbers, characters, or strings, etc. For example, "Hello, World!", 12, 23.0, "C", etc.

Literals are often used to assign values to variables or constants.
```
print("This is a hardcoded string or a literal")
```

Literal Examples:
```
//string
let someString: String = "Swift is fun" 
//unicode characters
let someCharacter: Character = "S"
//boolean
let pass: Bool = true  
//floating point
let piValue: Float = 3.14
```
There are four types of integer literals in Swift:

Type	Example	Remarks
-Decimal     5, 10, -68	 Regular numbers.
-Binary	     0b101, 0b11 Start with 0b.
-Octal	     0o13	 Start with 0o.
-Hexadecimal 0x13	 Start with 0x.

##**DataTypes:**

```
Float : 5.4
Int : 5
Character : A
String : Hi
Double  27.7007697012432
Bool true/false
```

###**Swift Basic Input and Output:**
```
print("Swift is powerful")

// Output: Swift is powerful
```
Here, the print() function displays the string enclosed inside the double quotation.

Syntax of print()

In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 3 parameters

`print(items: separator: terminator:)`
Here,

items - values inside the double quotation
separator (optional) - allows us to separate multiple items inside print().
terminator (optional) - allows us to add add specific values like new line "\n", tab "\t"

**print() with terminator:**
```
// print with terminator space
print("Good Morning!", terminator: " ")

print("It's rainy today")
Output

Good Morning! It's rainy today
```
Notice that we have included the terminator: " " after the end of the first print() statement.

Hence, we get the output in a single line separated by space.

**print() with separator**
`print("New Year", 2022, "See you soon!", separator: ". ")`
Output

New Year. 2022. See you soon!
In the above example, the print() statement includes multiple items separated by a comma.

Notice that we have used the optional parameter separator: ". " inside the print() statement. Hence, the output includes items separated by . not comma.

**concatenated strings**:
`print("one" + "two")`

**Print Variables and Strings together:**

```
var year = 2014
print("Swift was introduced in \(year)")
```

-Text: Swift was introduced in
-Variable: /(year)

**To take inputs in swift we use `readLine()`**
```
print("Enter your favorite programming language:")
let name = readLine()

print("Your favorite programming language is \(name!).")
```


##Comments
```
//single line comments

/*multi line
comments*/
```

##Optional

How to declare an Optional?
You can simply represent a Data type as Optional by appending ! or ? to the Type. If an optional contains a value in it, it returns value as Optional<Value>, if not it returns nil.

Example 1: How to declare an optional in Swift?
```
var someValue:Int?
var someAnotherValue:Int!
print(someValue)
print(someAnotherValue)
```
##**Operators:**


##Terninary

You can replace this code
```
// check the number is positive or negative
let num = 15
var result = ""

if (num > 0) {
     result = "Positive Number"
}
else {
     result = "Negative Number"
}

print(result)
```
with
```
// ternary operator to check the number is positive or negative
let num = 15

let result = (num > 0) ? "Positive Number" : "Negative Number"
print(result)

```

##Bitwise

Here's the list of various bitwise operators included in Swift

Operators	Name      Example
&	Bitwise AND	        a & b
|	Bitwise OR	        a | b
^	Bitwise XOR	        a ^ b
~	Bitwise NOT	        ~ a
<<	Bitwise Shift Left	a << b
>>	Bitwise Shift Right	a >> b


##**Flow Control:**

If else:

```
let number = 10

// check if number is greater than 0
if (number > 0) {
  print("Number is positive.")
}

print("The if statement is easy")

```
![if else](https://cdn.programiz.com/cdn/farfuture/ERV8oL5-f8HavxwOxEGpFVvMx1wjHqb78Pn-zUxkp_s/mtime:1618994409/sites/tutorial2program/files/swift-if-statement.png)


Switch:

a better approach of if else.

Example:
```
switch (expression)  {
  case value1:
    // statements 

  case value2:
    // statements 

  ...
  ...
        
  default:
    // statements
}

```
![switch](https://cdn.programiz.com/cdn/farfuture/xLoJgDQVxTGY721Bcn5p4geinUUk6r4d0WGDYOLeaeg/mtime:1619594067/sites/tutorial2program/files/swift-switch-statement.png)

Applied Example:

```
// program to find the day of the week 

let dayOfWeek = 4

switch dayOfWeek {
  case 1:
    print("Sunday")
	    
  case 2:
    print("Monday")
	    
  case 3:
    print("Tuesday")
	    
  case 4:
    print("Wednesday")
	    
  case 5:
    print("Thursday")
	    
  case 6:
    print("Friday")
	    
  case 7:
    print("Saturday")
	    
  default:
    print("Invalid day")
}
```

**LOOP**
a loop is a piece of code that will continue running until one or more value is as given.
for in:

```
for val in sequence{
  // statements
}
```

![loop](https://cdn.programiz.com/cdn/farfuture/VnHaNoAxPKR16dbzBzkIhnkn4qfFiw13hMjiqdLblWU/mtime:1619682225/sites/tutorial2program/files/swift-for-loop.png)

Example: Loop Over Array
```
// access items of an array 
let languages = ["Swift", "Java", "Go", "JavaScript"]

for language in languages {
      print(language)
}
```
for Loop with where Clause
In Swift, we can also add a where clause with for-in loop. It is used to implement filters in the loop. That is, if the condition in where clause returns true, the loop is executed.


```
// remove Java from an array

let languages = ["Swift", "Java", "Go", "JavaScript"]

for language in languages where language != "Java"{
  print(language) 
}
```

Swift while Loop
Swift while loop is used to run a specific code until a certain condition is met.

The syntax of while loop is:
```
while (condition){
  // body of loop
}
```
Here,

-A while loop evaluates condition inside the parenthesis ().
-If condition evaluates to true, the code inside the while loop is executed.
-condition is evaluated again.
-This process continues until the condition is false.
-When condition evaluates to false, the loop stops.

![while](https://cdn.programiz.com/cdn/farfuture/0xHV_5ctjEVbHWRySw6v6257B3JsOrICthRNMx14pBA/mtime:1620036799/sites/tutorial2program/files/swift-while-loop.png)

Example 1: Swift while Loop
```
// program to display numbers from 1 to 5

// initialize the variable
var i = 1, n = 5

// while loop from i = 1 to 5
while (i <= n) {
  print(i)
   i = i + 1
}
```

Guard:


Syntax of guard Statement
The syntax of the guard statement is:
```
guard expression else {
  // statements
  // control statement: return, break, continue or throw.
}
```
Here, expression returns either true or false. If the expression evaluates to

true - statements inside the code block of guard are not executed
false - statements inside the code block of guard are executed
Note: We must use return, break, continue or throw to exit from the guard scope.
Example:
```
var i = 2

while (i <= 10) {
    
  // guard condition to check the even number 
  guard i % 2 == 0 else {
   
     i = i + 1
    continue
  }

  print(i)
  i = i + 1
} 
```

The break statement is used to terminate the loop immediately when it is encountered.
The continue statement is used to skip the current iteration of the loop and the control flow of the program goes to the next iteration.


**Array:**
Array is a data structure that holds multiple data altogether

```
// an array of integer type
var numbers : [Int] = [2, 4, 6, 8]

print("Array: \(numbers)")  
```

Access Array Elements
In Swift, each element in an array is associated with a number. The number is known as an array index.

We can access elements of an array using the index number (0, 1, 2 …). For example,
```
var languages = ["Swift", "Java", "C++"]

// access element at index 0
print(languages[0])   // Swift

// access element at index 2
print(languages[2])   // C++
```
Add Elements to an Array
Swift Array provides different methods to add elements to an array.

1. Using append()

The append() method adds an element at the end of the array. For example,
`array.append(2)`
2. Using insert()

The insert() method is used to add elements at the specified position of an array. For example,

`array.insert(2, at: 1)`

**SET:**

Create a Set in Swift
Here's how we can create a set in Swift.
```
// create a set of integer type
var studentID : Set = [112, 114, 116, 118, 115]

print("Student ID: \(studentID)")
```
specify type of set:
`var studentID : Set<Int> = [112, 114, 115, 116, 118]`
-remove() - remove an element
-insert() - insert a value
-removeFirst() - to remove the first element of a set
-removeAll() - to remove all elements of a set
sorted()	sorts set elements
forEach()	performs the specified actions on each element
contains()	searches the specified element in a set
randomElement()	returns a random element from the set
firstIndex()	returns the index of the given element

**Dictionary:**
```
var capitalCity = ["Nepal": "Kathmandu", "Italy": "Rome", "England": "London"]
print(capitalCity)
```

Add Elements to a Dictionary
We can add elements to a dictionary using the name of the dictionary with []. For example,
```
var capitalCity = ["Nepal": "Kathmandu", "England": "London"]
print("Initial Dictionary: ",capitalCity)

capitalCity["Japan"] = "Tokyo"

print("Updated Dictionary: ",capitalCity)
print(capitalCity["Japan"])
```

 Dictionary Methods
Method	Description
sorted()	sorts dictionary elements
shuffled()	changes the order of dictionary elements
contains()	checks if the specified element is present
randomElement()	returns a random element from the dictionary
firstIndex()	returns the index of the specified element
removeValue() method to remove an element from the dictionary

**Tuple:**

Create A Tuple
In Swift, we use the parenthesis () to store elements of a tuple. For example,
```
var product = ("MacBook", 1099.99)
Here, product is a tuple with a string value Macbook and integer value 1099.99.
```
Like an array, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0.

We use the index number to access tuple elements. For example,
```
// access the first element
product.0

// access second element
product.1
// modify second value
product.1 = 1299.99
```


In Swift, we can also provide names for each element of the tuple. For example,
```
var company = (product: "Programiz App", version: 2.1)
company.product //access it
```

##**Functions:**

A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. In this case, we can create two functions:

a function to draw the circle
a function to color the circle
Hence, a function helps us break our program into smaller chunks to make our code reusable and easy to understand.

In Swift, there are two types of function:

User-defined Function - We can create our own functions based on our requirements.
Standard Library Functions - These are built-in functions in Swift that are available to use.
Let's first learn about user-defined functions.

Swift Function Declaration
The syntax to declare a function is:
```
func functionName(parameters)-> returnType {
  // function body 
}
```
Here,

func - keyword used to declare a function
functionName - any name given to the function
parameters - any value passed to function
returnType - specifies the type of value returned by the function
Let's see an example,
```
func greet() {
print("Hello World!")
}
```
Here, we have created a function named greet(). It simply prints the text Hello World!.

This function doesn't have any parameters and return type. We will learn about return type and parameters later in this tutorial.

Calling a function in Swift
In the above example, we have declared a function named `greet()`.
```
func greet() {
  print("Hello World!")
}
```
Now, to use this function, we need to call it.

Here's how we can call the greet() function in Swift.
```
// call the function
greet()
```

Working of Recursion in Swift
```
func recurse() {
  ... ...  
  recurse()
  ...  ...     
}
```
recurse()
Here, the recurse() function is calling itself over and over again. The figure below shows how recursion works.

![func](https://cdn.programiz.com/cdn/farfuture/XAoZyQnKV7TXpegz5z3SEgw_2hDTXk2sebkB6C23q2U/mtime:1622635027/sites/tutorial2program/files/swift-recursion.png)

In Swift, a closure is a special type of function without the function name. For example,
```
{
  print("Hello World")
}
```
Here, we have created a closure that prints Hello World.

Before you learn about closures, make sure to know about Swift Functions.

Swift Closure Declaration
We don't use the func keyword to create closure. Here's the syntax to declare a closure:
```
{ (parameters) -> returnType in
   // statements
}
```
Here,

parameters - any value passed to closure
returnType - specifies the type of value returned by the closure
in (optional) - used to separate parameters/returnType from closure body

```
// declare a closure
var greet = {
  print("Hello, World!")
}

// call the closure
greet()
```

If I try to cover OOP in this blog it will be a lot large 
so I will make a seperate blog about this .
[Buy me a coffee](https://www.buymeacoffee.com/tawhid)