In this Swift Tutorial blog, I am going to introduce you to some of the basic concepts of Swift. But, before moving ahead, I would get you guys familiar with “What is Swift” & how can you install Swift on your system. So, let’s get started now!!

In this blog on Swift Tutorial, I would be covering the following topics:

Once, you go to the link, select the latest version of Xcode available and download it by clicking on the given link near the disc image.

After downloading the dmg file, you can install it by simply double-clicking on it.

Alright!! So, once you have your xCode, just double-click on it to open and then go to File -> New and choose Playground. Then choose iOS and mention the playground’s name. Once you are done with that click on Create.

Fig 1: Creating Playground In Xcode IDE – Swift Tutorial

So, now that your playground is ready, let’s get started with some coding!

So, initially let’s start with basic syntax and then let’s write a hello world program.

Swift Tutorial: Basic Syntax

Tokens – A token is either a keyword, an identifier, a constant, a string literal, or a symbol.

Semicolons – In Swift you do not have to type a semicolon (;) after each statement in the code. Only in the case of using multiple statements in the same line, a semicolon is used as a delimiter.

Keywords – Keywords are reserved words in the coding languages which may not be used as constants or variables or any other identifier names unless they’re escaped with backticks(`…`).

Literals – A literal is mainly the source code representation of a value of an integer, floating-point number, or string type. So, a literal can be an Integer literal, Floating literal, String literal or a Boolean literal.

Comments – Comments help compilers to ignore the texts which are not to be compiled. Multi-line comments start with /* and terminate with */ whereas Single-line comments are written using // at the beginning of the comment.

Identifiers – Swift is a case-sensitive language and does not allow special characters such as @, $, and % within identifiers. An identifier starts with an alphabet A to Z or a to z or an underscore _ followed by more letters, underscores, and digits (0 to 9).

White spaces – Whitespace is used in Swift to describe blanks, tabs, newline characters, comments and also separate one part of a statement from another. This helps the compiler to identify where one element in a statement, ends and the next element begins.

Hello World Program

/*Hello World Program */
import UIKit // Since we are creating the program for iOS playground, we have to import UiKit
var myString ="Hello World!";print (myString)// Semicolon used since 2 statements are used together

Output:

Hello World!

Now, that you have written your first program, let’s understand more about variables and data types.

Get Certified With Industry Level Projects & Fast Track Your Career

Swift Tutorial: Variables, Datatypes & TypeCasting

Variables

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Swift Tutorial: Operators

Operators are the constructs which can manipulate the values of the operands. Consider the expression 7 + 3 = 10, here 7 and 3 are operands and + is called operator. Swift supports the following types of operators:

Fig 2: Different Operators In Swift – Swift Tutorial

Now, I’m not going to go in depth guys, but let me show you a few simple operations in Swift. Consider the example below:

First condition is satisfiedSecond condition is satisfiesValue of variable x is 100Value of variable y is 200

If-Else statement

If-else statement tests the condition and if the condition is false then ‘else’ statement is executed.

Fig 5: Flow Chart Of If – Else Conditional Statement – Swift Tutorial

Consider the example below:

var x:Int = 10
if x < 20 {
print("x is less than 20") }
else {
print("x is not less than 20")}
print("Value of variable x is (x)")

Output:

x is less than 20

If-else..if-else (If-else ladder)

Now, you can also have an if-else ladder. So, If-else-if ladder allows the user to use many if else statements within a loop and in case one of the condition holds true the rest of the loops is bypassed.

var x: Int = 100
var y:Int = 200
if x < y {
/* If condition is true then print the following */
print("x is less than y") }
else if x > y {
/* If condition is true then print the following */
print("x is greater than y") }
else {
/* If condition is false then print the following */
print("x is equal to y") }
print("Value of variable x and y are:(x) and (y)")

Output:

x is less than y
Value of variable x and y are: 100 and 200

Switch

The switch statement provides an easy way to execute conditions to different parts of the code.

Now, if you observe the output, even after our condition is satisfied, we are getting the next statement also printed. That’s because we are using the statement fallthrough. So, if you do not use a fallthrough statement, then the program will come out of the switch statement after executing the matching case statement.

Interested In Building Your Own iOS Apps??

Now, let’s move on to iterative loops.

Swift Tutorial: Iterative Loops

In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several times.

A loop statement allows us to execute a statement or group of statements multiple times. So, iterative loops are mainly For-In, While and Do-While loop.

For-In Loop

The for-in loop iterates over collections of items, such as ranges of numbers, items in an array, or characters in a string.

Fig 8: Flow Chart Of For-In Loop – Swift Tutorial

Consider the example below:

for i in 1...3 {
print("Hello world! and Value of i is (i)")
}

Output:

Hello world! and Value of i is 1Hello world! and the Value of i is 2Hello world! and Value of i is 3

While Loop

A while loop statement in the Swift programming language repeatedly executes a target statement as long as a given condition is true.

Alright, Guys! That’s an end to loops, now let’s quickly jump into Arrays & Tuples.

Swift Tutorial: Arrays & Tuples

Arrays

An array is a data structure that contains a list of elements. These elements are all of the same data type, such as an integer or string. So, suppose if you want to store the names of your friends. You can write a program as follows:

Alright, now that you guys have understood Arrays, it’s time to get started with sets and dictionaries.

Want To Get Certified In iOS Development??

Swift Tutorial: Sets & Dictionaries

Sets

Sets are used to store distinct values of same types, without having any definite ordering as that of arrays. So, you can use sets instead of arrays if you want to ensure that there are no duplicate values or if the ordering of elements is not an issue.A Set is created by placing all the items (elements) inside curly braces [], separated by a comma. Consider the example below:

let evenNumber: Set = [2,4,6,8,12]

Now, let me tell you that you can also perform the set operations such as Union, Intersection, Subtraction.

Union: Union of A and B is a set of all the elements from both sets. The union is performed using .union() method.

Intersection: Intersection of A and B is a set of elements that are common in both sets. An intersection is performed using the .intersection() method.

Subtracting: Difference of A and B (A – B) is a set of elements that are only in A but not in B. Similarly, B – A is a set of elements, i.e. in B but not in A. Refer to the code below:

Value of key = 1 is Optional("One")Value of key = 2 is Optional("Two")Value of key = 3 is Optional("Three")

Swift Tutorial: Functions

A function is basically a set of statements organized together to perform a specific task. You can call a function, have a function with/without parameters, have a function with/without return values, have function types, and also use nested functions. Refer to the example below, to understand how to define and call functions. Consider the example below:

Now, let’s move to the next section of the blog i.e. Closures & Structures.

Swift Tutorial: Closures & Structures

Closures

Closures generally confuse everyone, but they are just self-contained codes, like function organized as blocks. They can be anonymous whereas function has to have a function name. Consider the example below.

let name = { print("Welcome to Swift Closures") }
name()

Output:

Welcome to Closures

Structures

Swift provides a flexible building in any coding platform block of making use of constructs as Structures. By making use of these structures once can define constructs methods and properties. Consider the example below.

Swift Tutorial: Extensions

Extensions are basically used to add the functionalities of an existing class, structure or enumeration type. With extensions, you can add computed properties and computed type properties, define and use new nested types, define instance and type methods, provide new initializers, define subscripts, and also make an existing type conform to a protocol.