iOS Swift Tutorial
IOS Development

iOS Swift Tutorial – Learn Language Basics

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 which can be manipulated later in your program.

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

iOS Swift Tutorial create playground

iOS Swift Tutorial save playground

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

iOS Swift Tutorial variable name error

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"

iOS Swift Tutorial define string variable

String Interpolation

To print a string and include a value of a different type, you can convert it using string interpolation \()  like this:

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

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:

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:

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

iOS Swift Tutorial constant change error

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.

iOS Swift Tutorial define array

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

iOS Swift Tutorial array append

You can check the array count like this:

myarr.count

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

iOS Swift Tutorial array remove item

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:

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 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,

iOS Swift Tutorial define dictionary

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

iOS Swift Tutorial dictionary processing

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

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:

iOS Swift Tutorial repeat while loop

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:

iOS Swift Tutorial for loop

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

 

If-else Statements

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

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

Also, you can use an else statement like this:

iOS Swift Tutorial if else statement

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

iOS Swift Tutorial multiple if else

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:

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

iOS Swift Tutorial modulus operator

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:

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

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

You can define the return type like this:

Notice the return type is Int.

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

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.

iOS Swift Tutorial define function

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

iOS Swift Tutorial call function

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 enable 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:

 

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

The class that we’ve just created is just the blueprint and in order 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:

iOS Swift Tutorial call class function

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

iOS Swift Tutorial multiple class instances

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:

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

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:

iOS Swift Tutorial inheritance

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 a different parameters and every function does a different job.

Here we have a book class which 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 totally different job, but the only condition is you MUST have different parameters for every one of them.

iOS Swift Tutorial polymophism

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

Cool!!

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

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

Thank you.

  • winprg

    Thank you for this tutor, I wanted to know how to use Swift on beginning point. only seen some huge docs on Apple site… it was a book, not docs, with much of blablabla…

  • winprg

    Fix pls, 2 typos: a) +10 in loop must be +1 to take all items, b) motorcar–motocar.

    • Sorry for the typos. Now fixed.
      Thank you very much for your notice.