Swift Tutorial – Fundamentals for iOS Development
Do you want to learn basic concepts of Swift programming language? Here is a comprehensive guide to getting started with Swift and we cover the following topics in this Swift Tutorial.
- 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?
Swift is a popular programming language used in iOS and OS X development. It is completely based on C and Objective C and it is developed by Apple Inc.
Installing 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
/*Hello World Program */
import UIKit // Since we are creating the program for the iOS playground, we have to import UiKit
var myString =”Hello World!”;print (myString)// Semicolon used since 2 statements are used together
Output
Hello World!
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
var a = 42 //Declaring variable
var a: Int = 42 // You can also declare variable by specifying the data type.
let b = 32 // Declaring a constant
print(varA)
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.
Type Casting
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
let a: Int = 5679 // Declare 2 constants
let b: Float = 2.9999
//Converting Float to Int
print(“This number is an Int now (Int(b))”)
//Converting Int to Float
print(“This number is a Float now (Float(a))”)
Output
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.
Type | Operator |
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.
print(” 5 + 3 = (5 + 3 ) “) // Addition
print(” 5 – 3 = (5 – 3 ) “) // Subtraction
print(” 5 * 3 = (5 * 3 ) “) // Multiplication
print(” 5 / 3 = (5 / 3 ) “) // Division
print(” 5 % 3 = (5 % 3 ) “) // Modulus
Output
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.
If 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
var x:Int = 10
if x < 20 {
print(“x is less than 20”) }
print(“Value of variable x is (x)”)
Output
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
var x:Int = 100
var y:Int = 200
if x == 100 {
print(“First condition is satisfied”)
if y== 200 {
print(“Second condition is also satisfied”) }
}
print(“Value of variable x is (x)”)
print(“Value of variable y is (y)”)
Output
First condition is satisfied
Second condition is satisfies
Value of variable x is 100
Value of variable y is 200
If-Else Statement
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
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 Ladder
It allows the developer to use more than one if-else statement within a loop. If the conditional holds true, the rest of the loops will be bypassed.
Example for If-Else Ladder in Swift
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 Statement in Swift
The switch statement is the easy way for executing conditions that have multiple parts.
Example for Switch Statement in Swift
var a = 20
switch index {
case 10 :
print( “Value of index is 10”)
fallthrough
case 15,20 :
print( “Value of index is either 15 or 20”)
fallthrough
case 30 :
print( “Value of index is 30”)
default :
print( “default case”) }
Output
Value of index is either 15 or 20
Value of index is 30
Iterative Loops in Swift
The loop statements also known as iterative loops are used to execute a group of statements multiple times. Popular loop statements are for-in loop, while loop, and do-while loop 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
for i in 1 … 3
{
print (“Hello World! And Value of i is (i)”) }
Output
Hello World! And Value of i is 1
Hello World! And Value of i is 2
Hello World! And Value of i is 3
While Loop
Here, the statements within the while block will be repeatedly executed until the given condition becomes true.
Example for While Loop in Swift
var current: Int = 0 //Initialize variables
var final: Int = 3
let Completed = true
while (current <= final) // condition
{ //play game if Completed
{
print(“You have passed the level (current)”)
current = current + 1 //statement to be executed if the condition is satisfied
}
}
print(“The while loop ends”) //Statement executed after the loop ends
Output
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
Do-While Loop
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
var val = 5 repeat
{ print(“Value is (val)”)
val = val + 1 }
while index < 10.
Output
Value is 5
Value is 6
Value is 7
Value is 8
Value is 9
Arrays in Swift
Arrays are a data structure that consists of a list of elements that are in similar data types. An example for an array is as follows
var color: Array <String> = [“Green”, “Red”, “Blue”, “Purple”]
the append method is used to add more elements to an array. For example,
color.append(“Yellow”)
print (color)
Output
Green Red Blue Purple Yellow
Tuples in Swift
Tuples are used for grouping the multiple values in a single value. For example,
var failure404 = (404, “Gateway not found”)
print(“The code is(failure404.0)”)
print(“The definition of error is(failure404.1)”)
var failure404 = (failureCode: 404, description: “Gateway not found”)
print(failure404.faliureCode) // prints 404.
Ouput
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.
let evenNumber: Set = [4,6,2,8,10]
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
let evenNumber: Set = [10,12,14,16,18,20]
let oddNumber: Set = [5,7,9,11,13,15]
let primeNumber: Set = [2,3,5,7,13,17,19]
oddNumber.union(evenNumber).sorted()
oddNumber.intersection(evenNumber).sorted()
oddNumber.subtracting(primeNumber).sorted()
Output
[5,7,9,10,11,12,13,14,15,16,18,20]
[]
[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
var exampleDict:[Int:String] = [1:”One”, 2:”Two”, 3:”Three”] //Creating Dictionaries
var accessval = exampleDict[1] //Accessing Dictionary Values
print( “Value of key = 1 is (accessVal” )
print( “Value of key = 2 is (exampleDict[2])” )
print( “Value of key = 3 is (exampleDict[3])” )
Output
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
func Employee(empname: String) -> String {
//Defining a function
return empname }
print(Employee(empname: “Jack”)) //Calling a function
print(Employee(empname: “Jill”))
Output
Jack
Jill
Closures in Swift
Closures are self-contained codes that can be anonymous, unlike functions. An example of closure is as follows
let name = { print (“Example for Closures in Swift”)}
name()
Output
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
struct employeeDetails { //Defining a Structure
var name = “Jack”
var id=121
varphonenumber= 9958746521
}
let details = employeeDetails() //Accessing the structure and properties
print(“Name of employee is (details.name)”)
print(“Id of employee is (details.id)”)
print(“Phone number of employee is (details.phonenumber)”)
Output
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
class DetailsStruct { //Defining a class
var id:Int
init(id:Int) {
self.id= id }
}
class studentDetails {
var id=4577845
}
let studentid = studentDetails()
print(“Student id is (studentid.id)”)
Output
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
class EmployeeDetails{
var id:Int;
var number:Int;
init(detail1:Int, detail2:Int) {
id = detail1;
number = detail2;
}
func print() {
print(“Employee id is :(id), Employee phone number is :(number)”)
}
}
class display : EmployeeDetails {
init() {
super.init(detail1:8754, detail2: 9875646531) //super keyword is used to call the parameters & methods from super class
}
}
let employeeinformation = display()
employeeinformation.print()
Output
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
protocol Fly {
var flies: Bool { get set }
func flyable(milesCovered: Double) -> String
}
class Vehicle : Fly{
var flies: Bool = false
var name: String = “Default name”
func flyable(milesCovered: Double) -> String {
if(self.flies){
return “(self.name) flies (milesCovered) miles”
}
else {
return “(self.name) cannot fly”
}
}
}
var BMWX1 = Vehicle()
BMWX1.name = “BMW X1”
BMWX1.flies = false
print(BMWX1.flyable(34))
Output
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
extension Int{
var add:Int{returnself+10}
varsubtract:Int{returnself- 34}
var multiply:Int{returnself* 5}
var divide:Int{returnself/5}
}
let addition = 3.add
print(“The value after adding is (add)”)
let subtraction = 120.subtract
print(“The value after subtracting is (subtraction)”)
let multiplication = 25.multiply
print(“The value is mutiplying is (multiplication)”)
let division = 55.divide
print(“The value after division is (division)”)
let mix = 10.add+34.subtract
print(“Value calculated is (mix)”)
Output
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
func swap<T>(x: inout T, y: inout T){
let temp = x
x = y
y= temp
}
var str1 =”Hello”
var str2 =”Edureka”
print(“Before Swapping String values are: (str1) and (str2)”)
swap(x:&str1, y:&str2)
print(“After Swapping String values are: (str1) and (str2)”)
var num1 = 1996
var num2 = 1865
print(“Before Swapping Int values are: (num1) and (num2)”)
swap(x:&num1, y:&num2)
print(“After Swapping Int values are: (num1) and (num2)”)
Output
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
enum Color: Int {
case blue
case green
case red
case yellow
init() {
self = .red
}
func getDetails() -> String {
switch(self){
case .blue: return “Color is blue”
case .purple: return “Color is purple”
case .red: return “Color is red”
case .yellow: return “Color is yellow”
default: return “Color not found” }
}
}
var chooseColor = Color
print(chooseColor.rawValue)
var favColor = Color.purple
print(favColor.rawValue)
if(favColor == Color.purple)
{
print(“Favourite color is Purple”)
}
print(favColor.getDetails())
Output
2
1
Favorite Color is Purple
Purple
Conclusion
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.