Swift Tutorial – Fundamentals for iOS Development
- What is Swift?
- Installing Swift
- Syntax of Swift
- Variables, Data Types, & Type Casting
- Operators in Swift
- Conditional Statements
- Iterative Loops
- Arrays and Tuples
- Sets and Dictionaries
- Functions of Swift
- Closures and Structures
- Protocols and Extensions
- Generics and Enumerations
What is Swift?
Before installing Swift programming language, check out the following prerequisites in your system
- Memory: 1 GB
- Graphics Card: NVIDIA GeForce 510
- File Size: 700 MB
- OS: Windows XP or above
- Software: XCode IDE
For downloading XCode, go to the Apple Developer Website and then to Download for Apple Developers. Now, select the latest version of XCode and download it. Once you have downloaded the dmg file, then you can start installing by double-clicking on it.
When the installation is done, double-click on it to open and go to File -> New -> Playground. Now, choose iOS and mention the name of the playground. Click on create.
Now we have created a playground in XCode IDE. As the playground is ready, we can start with coding.
Syntax of Swift
Following is a list of the popular syntax of Swift programming language. It is important to have a fundamental understanding of them for writing code properly.
Tokens: It refers to a keyword, a constant, a string, a symbol, or an identifier as per the place it is used.
Semicolons: Generally, semicolons will not be used in every statement of the code in Swift. It is used as a delimiter when using multiple statements in the same line.
Keywords: They are reserved words in the swift coding language.
Literals: It is mainly used for source code representation of a value of an integer, string type, or a floating-point number.
Comments: They define texts that are to be ignored by the compiler and they will be used within /* and */ for multiple lines of comments and // for single-line comments.
Identifier: As swift is a case-sensitive programming language, it doesn’t allow special characters like @, #, $, %, and so on within identifiers. The identifier must contain A to Z or a to z or underscore or digits.
White Spaces: In Swift, Whitespace is used to denote tabs, blanks, newline characters, statements, or comments. It helps the compiler identify the status of statements.
Sample Hello World Program with Swift
Variable, Data Types, and Type Casting in Swift
Variables in Swift
The variables are reserved memory locations for storing given values. In simple terms, whenever you create a variable, it means you are reserving memory for upcoming values.
Sample Variable Declaration
Data Types in Swift
Swift provides various built-in data types as follows
|Data Type||Bit Width||Range|
|Int8||1 byte||-127 to 127|
|UInt8||1 byte||0 to 255|
|Int32||4 bytes||-2147483648 to 2147483647|
|UInt32||4 bytes||0 to 4294967295|
|Int64||8 bytes||-9223372036854775808 to 922337203685477580|
|UInt64||8 bytes||0 to 18446744073709551615|
|Float||4 bytes||1.2E-38 to 3.4E+38 (˜6 digits)|
|Double||8 bytes||2.3E-308 to 1.7E+308(˜15 digits)|
In Swift, it is not necessary to define the data type when declaring a variable as it automatically understands the type according to the value.
In swift, you can perform type casting or type conversion as follows
Here is the example of converting the integer value to a float value using type casting
This number is an Int now 2
This number is a Float now 5679.0
Operators in Swift
Operators are used to manipulating the value of the operands. For example, for the addition operation, + is the operator. Following are the operators that are supported by Swift Programming.
|Arithmetic Operators||+, -, *, /, %|
|Comparison Operators||==, !=, >, <, >=, <=|
|Logical Operators||&&, ||, !|
|Bitwise Operators||&, |, ^, ~, <<, >>|
|Assignment Operators||=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, !=|
|Range Operators||Closed Range, Half-Open Range, One-Sided Range|
|Miscellaneous Operators||Unary Minus, Unary Plus, Ternary Conditional|
Check out the following examples to understand the operators better.
5 + 3 = 8
5 – 3 = 2
5 * 3 = 15
5 / 3 = 1
5 % 3 = 2.3
Conditional Statements in Swift
Conditional Statements are the important thing in Swift programming as they are used to execute a group of statements as per the given condition like true or false. There are three different conditional statements such as If, If-Else, and Switch statement.
It is used for decision-making purposes to decide whether a particular statement or a group of statements will be executed or not.
Example for if statement in Swift
x is less than 20
Value of variable x is 10
Nested-If in Swift
The if statement within another if statement is known as nested if.
Example for Nested If in Swift
First condition is satisfied
Second condition is satisfies
Value of variable x is 100
Value of variable y is 200
Here, it tests the condition and if the condition is true, the statements in the ‘if’ block will be executed, or the statements in the ‘else’ block will be executed.
Example for If-Else in Swift
x is less than 20
Example for If-Else Ladder in Swift
x is less than y
Value of variable x and y are: 100 and 200
Switch Statement in Swift
The switch statement is the easy way for executing conditions that have multiple parts.
Example for Switch Statement in Swift
Value of index is either 15 or 20
Value of index is 30
Iterative Loops in Swift
For-In Loop in Swift
It is used to iterate the group of statements until the given condition becomes false.
Example for For-In Loop in Swift
Hello World! And Value of i is 1
Hello World! And Value of i is 2
Hello World! And Value of i is 3
Here, the statements within the while block will be repeatedly executed until the given condition becomes true.
Example for While Loop in Swift
You have passed the level 0
You have passed the level 1
You have passed the level 2
You have passed the level 3
The while loop ends
When the while loop is used to check the condition at the top of the loop, the do-while loop checks the condition at the bottom of the loop.
Example for Do-While Loop in Swift
Value is 5
Value is 6
Value is 7
Value is 8
Value is 9
Arrays in Swift
the append method is used to add more elements to an array. For example,
Green Red Blue Purple Yellow
Tuples in Swift
Tuples are used for grouping the multiple values in a single value. For example,
The code is 404
The definition of error is Gateway not found 404
Sets in Swift
Sets are used to store values of the same types without any proper ordering as for arrays. They are created by placing all the elements inside the curly braces  and a comma to separate the elements.
We can perform set operations like Union, Intersection, and Subtraction in Swift
Union: Union of A and B denotes the elements of both sides and it can be performed using the .union() method.
Intersection: Intersection of A and B denotes the common elements from both sides. It is performed using the .intersection() method.
Subtraction: The elements that are differ from A and B sets will be performed using A – B.
Example for sets in swift
[9, 11, 15]
Dictionaries in Swift
Dictionaries are used in swift to store unordered list of values that are in similar data types. Example for dictionaries in Swift
Value of key = 1 is Optional(“One”)
Value of key = 2 is Optional(“Two”)
Value of key = 3 is Optional(“Three”)
Functions in Swift
Functions are a set of statements coded together for performing a particular task again and again. It can be called with or without parameters, with or without return values, or function types. It can be used as nested functions. Example for functions in swift is as follows
Closures in Swift
Closures are self-contained codes that can be anonymous, unlike functions. An example of closure is as follows
Example for Closures in Swift
Structures in Swift
Structures are used to define construct methods and properties as swift offers a flexible solution for using coding blocks to be used as constructs.
Example for Structures in Swift
Name of employee is Jack
Id of employee is 121
Phone number of employee is 9958746521
Classes in Swift
Classes are the building blocks of flexible constructs. Users can also define classes with properties and methods to be used repeatedly.
Example for classes in swift
Student id is 4577845
Inheritance in Swift
Inheritance is the process of creating new classes using the properties and methods of existing classes. In simple terms, the derived class can get the capabilities of the base class along with its functions.
Here, the classes are divided into two categories like superclass and subclass
Superclass: A class that contains methods, properties, and functions to be used in other classes is known as a superclass.
Subclass: A class that inherits the properties, methods, and functions from the superclass in known as subclass. Example for Inheritance is below
Employee id is 8754, Employee phone number is 9875646531
Protocols in Swift
Interfaces in other programming languages are referred as protocols in Swift. Example for protocols in Swift is as follows
BMW X1 cannot fly
Extensions in Swift
Extensions are used in swift to add the functionalities of an existing class, structure, or enumeration and we can add computed properties, computed type properties, define new nested types, define instance and type methods, provide new initializers, define subscripts, and make an existing type conform to protocols.
Example for extensions in Swift
The value after adding is 13
The value after subtracting is 86
The value is multiplying is 125
The value after division is 11
Value calculated is 20
Generics in Swift
Generics are used to write flexible and reusable functions and types in Swift. They are used to avoid duplications in Swift codes.
Example for generics in Swift
Before Swapping String values are: Hello and Edureka
After Swapping String values are: Edureka and Hello
Before Swapping String values are: 1996 and 1865
After Swapping String values are: 1865 and 1996
Enumerations in Swift
Enumeration is a user-defined data type that contains a set of related values using the keyword enum. An example of enumeration in Swift is as follows
Favorite Color is Purple
We hope you have got a fundamental idea of Swift Programming Language through this blog. Gain hands-on exposure by implementing them in the real-time project by enrolling in our iOS Training in Chennai at Softlogic System.