Swift is a very easy programming language to learn as its syntax is easy to follow. In this iOS Swift tutorial, we will cover some of the Swift language fundamentals and we will see how EASY it is to develop using Swift programming language.

Before we start building iOS apps, we need to understand the Swift language basics and see how things work together then we can build the amazing apps we need. In this tutorial and all upcoming tutorials, we will use Swift 3.

Defining variables

Variables are used to store values that can be manipulated later in your program.

First, let’s create a new playground and save it. Then clear all playground content.

To define a variable, use the keyword var followed by the variable name like this:

var myvar

You can use any name for your variable, but you can’t start your variable name with a number like:

var 2myvar

The above definition is not correct, but you can include numbers like this:

var myvar2

Use any variable name you want, but be descriptive.

To assign a value for that variable, use the equal sign like this:

var myvar = "Hello LikeGeeks Visitors, Welcome to iOS Swift Tutorial"

String interpolation

To print a string and include a value of a different type, you can convert it using string interpolation

\()

like this:

var var1 = 100 var var2 = "Hello, I have $\(var1) in my pocket"

You are not limited to string variables, there are different types of variables that you can define in Swift.

var var1 = true var var2 = 50

The first variable var1 is a Boolean type. You can use true or false for Boolean types.

The second variable var2 is an integer type or Int as the Swift language names it.

In Swift, you don’t need to type the variable type and this due type the type inference.

Xcode detects the variable type based on the value provided, so if you assign a value for a variable between quotations, that means the variable is a string and if you type an integer as a value, that means the variable type is Int, etc,

You can explicitly define the variable type like this:

var var1: String = "Welcome To Swift Tutorial" var var2: Bool = true var var3: Int = 50

You don’t need to explicitly define these types, but sometimes it’s necessary as we’ll see later in the future posts.

Defining constants

Constants are like variables with one exception, if it takes a value, you can’t change it.

To define a constant, use the let keyword like this:

let var1 = "Welcome To Swift Tutorial" let var2 = 100 let var3 = true

If you try to change any of these constants, Xcode will show you an error to change the let to var so it can be modified

let var1 = "Welcome To Swift Tutorial" let var2 = 100 let var3 = true var1 = "Hello"

Working with arrays

The array is a set of values, so instead of defining numerous variables, you can define an array that holds all those values.

You can define an array like this:

var myarr = [10, 20, 30, 40, 50]

You can access any element of the array by the index which is zero-based, so the first element has the index of zero.

To append items to the array, use the append function like this:

var myarr = [10, 20, 30, 40, 50] myarr.append(60)

You can check the array count like this:

myarr.count

Also, you can remove items from the array using the remove function like this:

var myarr = [10, 20, 30, 40, 50] myarr.remove(at:3)

The index is zero-based, so 3 means the fourth element.

If you need to define an empty array, you can do it like this:

var myarr = [String]()

You must define the type explicitly which is a string in this case.

Defining dictionaries

Dictionaries are like arrays but they are key-value pairs where the key must be unique.

Sometimes it’s better to use a dictionary over an array because it’s much easier to find particular items.

When using arrays, the items ordered numerically, but if you need to find a specific piece of information, the dictionary is better.

You can define a dictionary like this:

var mydictionary = [String: String]()

Here we define a dictionary with a key of string type and the corresponding values are strings also.

To add items to the dictionary,

mydictionary["OS"] = "Mac OS" mydictionary["Mobile"] = "iPhone"

You can get the dictionary count like this:

mydictionary.count

Also, you can check if your dictionary is empty or not like this:

mydictionary.isEmpty

If you need to remove an element, you can do it like this:

mydictionary["OS"] = nil

And to iterate over the items, you can use the for-in loop like this:

for (mykey, myval) in mydictionary{ print(mykey + " ==> " + myval) }

To clear dictionary items use [:]

mydictionary = [:]

While loops

Now you create arrays and get any element by its index, it’s time to iterate over those elements and make something with them.

To iterate over array elements, you can use the while loop like this:

var myarr = [10, 20, 30, 40, 50] var x = 0 while x < myarr.count { myarr[x] = myarr[x] + 10 x = x + 1 } myarr

As you can see the result, the array elements increased by 10 for every element.

For-in loops

Another type of loops which is for-in loops. With for-in loop, you can iterate over a range of values.

You can write it like this:

var myarr = [10, 20, 30, 40, 50] for item in myarr { print(item) }

When using for-in loops, you don’t need an integer to increment each cycle like what you’ve done in the while loop.

If-else statements

You can use if statement to check for a certain condition like this:

var myvar = 100 if myvar == 100 { print("The Value is 100") }

You can see the results in the console window at the bottom.

Also, you can use an else statement like this:

var myvar = 100 if myvar == 100 { print("The Value is 100") } else { print("The value not equal 100") }

Maybe you have multiple conditions, you can use else if like this:

var myvar = 100 if myvar == 100 { print("The Value is 100") } else if myvar > 100 { print("The value is greater than 100") } else { print("The value is less than 100") }

Comparison operators

In the above example, we use the equal operator ==, however, there are other operators that you can use for comparison.

Not equal to: !=

Greater than: >

Greater than or equal to: >=

Less than: <

Less than or equal to: <=

You can use any of them the same way as the above example.

Math operations

In Swift, there are many operators that you can use to perform mathematical operations.

You can perform the four basic arithmetic operations (+ – * /) like this:

var sum = 5 + 5 var diff = 10 - 5 var multiply = 5 * 5 var divid = 25 / 5

You can use the modulus operator like any other programming language.

The modulus operator is used to get the remainder left when dividing two numbers.

var remain = 20 % 3

Swift functions

When you start coding, you will find at some time that there are some lines of code repeated all over your files.

You can group those lines in a function and write it once and call it many times anywhere.

To define a function, use the keyword func like this:

func myfunc(){ // Your code goes here }

This is the simplest function form. You can pass inputs or parameters to the function like this:

func myfunc(var1: Int, var2: Int){ // Your code goes here }

In this example, we define a function that takes two parameters of type Int.

You can define the return type like this:

func myfunc(var1: Int, var2: Int) -> Int { // Your code goes here }

Notice the return type is Int.

Let’s make a function that adds two numbers and return the sum.

func getsum(var1: Int, var2: Int) -> Int{ return var1+var2 }

Now the function is ready, all we have to do is to call it by its name:

getsum(var1: 10, var2: 15)

As you can see in the right pane, the result is 25.

Try to call the function different times with different inputs and check the result.

Object-Oriented programming

OOP or Object-Oriented Programming is a very popular model for programming where you construct everything as an object as in real life.

Classes are the main component of Object-Oriented Programming which enables you to create a blueprint for your object.

Creating a class in Swift is super easy, you can use the class keyword to create it like this:

class car { }

You can add variables for the properties of this class like this:

class car { var speed = 400 var model = "B.M.W" var engine = "" func move() { } func stop() { } }

The class that we’ve just created is just the blueprint and to use, you need to create an instance of it like this:

let mycar = car()

To create an instance of a class in Swift just put parentheses after its name like above.

After we create the instance, the created instance has an empty engine, so let’s give it a value.

mycar.engine = "power engine"

Also, you can call the functions of the class like this:

mycar.move() mycar.stop()

You can create multiple instances you want and every one of them will have its properties.

let mycar = car() mycar.engine = "power engine" let brocar = car() brocar.engine = "bro engine" let wifecar = car() wifecar.engine = "wife engine"

Object inheritance

You’ve created a class and it does its job well, now you need to create another class that does a similar job but with some difference, so instead of rewriting what you’ve done in the first class again, you can inherit that class and add or modify what you need.

Assume our car class is the base class or the parent class:

class car { var speed = 400 var model = "B.M.W" var engine = "" func move() { print("Moving...") } func stop() { } }

Now let’s create a child class from that class.

class motocar: car { }

The above code inherits all properties and functions of the car class to the motocar and this because of using the colon.

Maybe you need to override some functions in your new class, you can override it using override keyword like this:

class motocar: car { override func move() { print("Move fast....") } }

If you create an instance of motocar class and try to call the move function, you should see the overridden message.

Object polymorphism

Another important concept in OOP called polymorphism which allows you to have the same function name multiple times but every one of them has different parameters and every function does a different job.

class book { func copy() { print("copying paper book") } func copy(path: String) { print("copying pdf book") } }

Here we have a book class that has two functions with the same name, but if you look deeply, you will notice that the passed parameters are different.

The first copy function passes nothing while the second one passes one string parameter.

You can have many functions with the exact name and every one of them does a different job, but the only condition is you MUST have different parameters for every one of them.

As you can see, when I create an instance of that class it shows me both versions of the copy function.

Cool!!

In future posts, we will start exploring the Xcode environment and see how to build iOS apps.

I hope you find the post useful. Keep coming back.

Thank you.