Google News
Swift Interview Questions
Swift is a powerful and intuitive programming language for iOS, iPadOS, macOS, tvOS, and watchOS. Apple Inc. is the company behind it. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast.
It is based on the Objective C runtime library, which enables the execution of C, Objective C, C++, and Swift code in the same program. 
Swift has been integrated with Xcode since version 6, 7, 10.x, 11.x, 13.x and is built with the open-source LLVM compiler and can be used for creating both the front end and back end functionalities of applications.

Xcode supports source code for the programming languages: C, C++, Objective-C, Objective-C++, Java, AppleScript, Python, Ruby, ResEdit (Rez), and Swift, with a variety of programming models, including but not limited to Cocoa, Carbon, and Java. Third parties have added support for GNU Pascal, Free Pascal, Ada, C#, Go, Perl, and D. etc,.
Following are the features of Swift :
* Type Safety and Type inference language
* Protocol oriented
* Safe by default
* Enforced initializers
* Forced Unwrapping
* Less code, fewer files
* Closures
* Tuples
* Much faster when compared to other languages.
* More impressive structs and enums
* Not required to use semicolons
Swift programming language has speedily become one of the quick-growing languages in memoir. Swift makes us develop software that is incredibly fast, robust and secure.
This language is the most useful programming language that is used to develop an application for macOS and iOS(iPad and iPhone).
There are some important advantages offered by developing apps for macOS and iOS using swift.
Open-source language : The Swift programming language has been created as an open-source and is being open to everyone, this makes it simple for the program to upgrade all the source codes, email lists and bug tracker at regular intervals.

Easy to learn and maintain : Swift programing language is more simple and accurate when compared to C/C++. Apple evolved its programing language to be easy to use and syntaxes are taken from programming languages such as C#, Python, and Ruby. These simple syntax of this programing language make it more meaningful. In swift, all the content of the implementation (.m) and header (.h) files are combined in a single file that is (.swift).

Supported by multiple devices : Swift programming language is not just limited to support Apple devices, it will also support multiple devices of the technology world like Linux and Windows devices.

Supports dynamic libraries : Dynamic libraries are the executable chunks of the code that can be connected to an app. This feature allows the latest swift programing language. In swift, dynamic libraries are directly uploaded to the memory, thereby resulting in deduction down on the initial size of the app and finally increases app performance.

Optional types : An optional in swift is a type that can be held either as a value or not. To declare an optional, we can use a question “?” mark.

Closures : Closures are self-contained blocks of functionality that can be passed around and used in our code.
In Swift, question mark "?" is used in property declaration. It tells the compiler that this property is optional. The property may hold a value or not. It avoids runtime errors when accessing that property by using ?. This is useful in optional chaining and a variant of this example is in conditional clauses.
Syntax :
var optionalName : String? = "Chanti"  
if optionalName != nil {  
    print("Your name is \(optionalName!)")  
Swift supports several types of operators. One of them is Half Open Range operator. The half open range operator specifies a range between two values a and b (a<b) where b is not included. It is known as half open range operator because it contains its first value only not the final value.
Functions are the set of codes used to perform specific task. In Swift programming language, functions are used to pass local as well global parameter values inside the function's call.
In Swift4, functions can be categorized in two types :
* User Defined Functions
* Built-in Functions (Library Functions)
Functions and methods can be used interchangeably, but there is a small difference between both of them.  Methods belong to struts, classes, and enums, but functions do not.

Syntax : 
func thisIsAFunction1() {


struct Person {
func thisIsAMethod1() {

Swift provides a standard set of built-in data types which are used for different purposes :
Int : It is used to store the integer value

String :
String literals are used to define the text that contains double quotes in Swift.

Double and Float :
They are used in Swift when we have to define decimal value or number.

Arrays :
Arrays are defined for the collection of list items.

Bool : It is used to store the Boolean value. It uses ‘True’ and ‘False’ conditions

Dictionaries :
A dictionary is used to collect items of a similar type that is connected with a unique key.
Dictionary is similar to the hash tables in other programming languages. It speeds up the entries available in the table. Each entity uses its key in the table, which can be of any Boolean type such as string or number. These keys can be used to retrieve the concurrent value that can be of any value.
Following are some tools used to develop iOS applications :
Xcode : It is an iOS development tool that is used for both iOS apps and MAC OS. The graphic interface in Xcode is used to write code for iOS 8 with Apple’s Swift programming language.

Alcatraz : If you want to add Xcode in your application, you can use Alcatraz. It worked as a package manager for Xcode and used to install multiple plug-ins in your IDE. This tool is only available for Xcode 5+ and OSX 13.x+.

Marvel : It will convert sketches into collective prototypes. We can add paper sketches to the app, Adobe Creative Cloud, from Dropbox or we, can draw the sketch directly to the app. After adding the sketch, add tappable hot spots in your image to connect screens together. Now, you can export your web clip on a home page.

Cocoa Controls : It is a list of code used in iOS applications which includes more than 1000 libraries from the open-source community.
Automatic Reference Counting is used by Swift (ARC) in order to do memory management. This is the same thing in Swift as it is in Objective C in terms of notion. When you assign or unassign instances of classes (reference types) to constants, properties, and variables, ARC keeps track of strong references to those instances and increases or decreases their reference count correspondingly. It frees up memory consumed by objects with a reference count of zero. Because value types are copied when assigned, ARC does not raise or decrease its reference count. If you don't declare differently, all references will be strong references by default.
The key difference between Upcast and Downcast in ios Swift is that upcasting from a derived to a base class can be verified at compile-time and will never fail to compile and Downcasts, on the other hand, can fail to compile since the precise class is not always known. It is possible that the UIView you have is a UITableView or a UIButton.
The fundamental difference between the "==" operator and the "===" operator in ios Swift is that the equal to "==" operator compares value types to see if the values are the same while the equivalent to "===" operator compares reference types to see if the references point to the same instance (both point to the same memory address) or not.  Let us consider the following example for understanding the difference between the two in a better way :
class Human: Equatable {
   let id: Int
   let nameOfPerson: String
   init(id: Int, nameOfPerson: String) { = id
       self.nameOfPerson = nameOfPerson
   static func == (left: Human, right: Human) -> Bool {
       return ==
let human1 = Human(id: 2, nameOfPerson: "Janvi")
let human2 = Human(id: 2, nameOfPerson: "Janvi")
Now, for the piece of code given below, we can say that the two human instances are equal since their id is the same. Therefore, "Equal Instances!" gets printed.
if human1 == human2 {
  print("Equal Instances!")
  print("Instances Not Equal!")
Now, for the piece of code given below, we can say that the two human instances are not equivalent even though their id is the same since they point to different areas in the Heap Area, that is, they point to different addresses. Therefore, "Instances are not Equivalent!" gets printed.
if human1 === human2 {
  print("Equivalent Instances!")
  print("Instances are not Equivalent!")
A function inside a function is called a nested function.
Syntax :
func function1() {    
    //statements of outer function    
    func function2() {    
        //statements of inner function    
Enum is also known as Swift Enumeration. Enum is a data type which contains a set of the related values. It is declared in a class and its values are accessed through the instance members of that class.
Syntax :
enum enum_name    
// values are described here    
Regular Expression : Regular expressions are the special string patterns that specify how to perform a search through a string.
Responder Chain : Responder Chain is a hierarchy of objects that obtain the opportunity to respond to the events.
Swift Dictionary is used to store the key-value pairs and access the value by using the key. It is just like hash tables in other programming languages.
You have to declare variables and constants before using it. Constants are declared by using let keyword and variables by var keyword.
Example :
var freetimelearn = "Free Time Learning"  
let fees = 100 
It is used to provide the default value for the variable.
let missingN1 : String? = nil
let realN1 : String = “Vikas”
let existentN1 : String = missingN1 ?? realN1
We can create constant in Swift programming by declaring a ‘let’ keyword. Below is the example where we use declare street as a constant in lieu of a variable. For this, we have to use let keyword :
let street: String = “7th Avenue”
var number: Int
street = “Side Street”
number = 10


We cannot change the value of constant in Swift. If we try to update the first line of the code, the Xcode will show an error for a simple reason. To change the value of the street, we can comment on the given line, so that it will not create any type of error.
let street: String = “7th Avenue”
var number: Int
// street = “Side Street”
number = 10
Following are the common execution states for a Swift iOS Application :
Not Running : In this state, the application is not launched, or the code is terminated by the system, and it will shut down the whole application.

Inactive : It is the transactional state of the lifecycle where the application is running in the background, but it is not able to initiate events.

Active : It is the main execution state in the programming where the application is running in the background and able to initiate the event.

Background : In this phase, the application is running in the background, and it is still able to execute the code.

Suspended : This state defines that our application is running at the background state, and the system suspends this application, and the application is not able to execute any code.
In Swift, a tuple is a group of different values. And, each value inside a tuple can be of different data types.
Suppose we need to store information about the name and price of a product, we can create a tuple with a value to store name (string) and another value to store price (float)
Create A Tuple : In Swift, we use the parenthesis () to store elements of a tuple. For example,
var product = ("MacBook", 1099.99)​
Here, product is a tuple with a string value Macbook and integer value 1099.99.
Access Tuple Elements : Like an array, each element of a tuple is represented by index numbers (0, 1, ...) where the first element is at index 0.
We use the index number to access tuple elements. For example,
// access the first element

// access second element
Example : Swift Tuple
// create tuple with two elements
var product = ("MacBook", 1099.99)

// access tuple elements
print("Name:", product.0)
print("Price:", product.1)
Output :
Name: MacBook
Price: 1099.99
Some of the differences between ios Swift and Objective C are as follows :
Comparison Parameter ios Swift Objective C
Type of Programming Language. ios Swift is an object-oriented and functional programming language. Objective C is a class-based object-oriented programming language.
Dynamic Libraries Dynamic Libraries are supported by ios Swift. For instance, system iOS and macOS libraries are dynamic. In other words, these applications will receive improvements from Apple’s updates without new build submission. Dynamic Libraries are not supported by Objective C.
Tuples Tuples are supported by ios Swift. Tuples are not supported by Objective C.
Usage of Semicolons Usage of Semicolons is not mandatory in ios Swift. Usage of Semicolons is mandatory in Objective C.
Method definition in Classes, Structures and Enumerations The definition of methods in Classes, Structures and Enumerations is allowed in ios Swift. The definition of methods in Classes, Structures and Enumerations is not allowed in Objective C.
Let us consider that the two arrays are declared as follows:
var firstArray = ["Ramana", "Raani"]
let secondArray = ["Srikanth", "Anusha"]
A thing to be noted is that the first array has been kept mutable so we can append the second array to it. The three ways in which we can append the second array to the first one are as follows:
* Using the method "append(contentsOf: )" - In this method, the contents of the second array are copied into the first array.
firstArray.append(contentsOf: secondArray)
* Using the "+=" operator - In this method also, the contents of the second array are copied into the first array.
firstArray += secondArray
* Appending two arrays by using the "+" operator and adding the result to a new array -
let thirdArray = firstArray + secondArray
The process of preparing an instance of an enumeration, structure, or class for use is known as initialization. Initializers are also used when a new instance of a type is created. An initializer is a no parameter instance method. The init keyword can be written using the initializer. Their primary role is to ensure that new instances of a type are correctly initialized before they’re used for the first time.
Its syntax is given below :
// New Instances are initialized here
The control transfer statements present in ios Swift are as follows :
Continue : The continue statement skips the current iteration of a loop and directs the program's control flow to the next iteration.

Break :
When the break statement is found, a loop is immediately terminated.

Return :
In Swift, the return statement is used in functions and methods to return values that meet our needs. In the Swift programming language, we can return values from functions/methods based on our requirements by utilising the return keyword.

Fallthrough :
The fallthrough keyword merely directs code execution to the statements contained in the following case (or default case) block.
Some common features in Swift structures and Swift classes are as follows :
* Swift Structs and Swift classes can both define attributes for storing values and functions.

With init, both structures and classes in Swift can create initializers to set up their initial state ()

They can be extended using extensions.

They can follow protocols, such as those used in Protocol Oriented Programming.

They can collaborate with generics to create types that are adaptable and reusable.
Given below are some features which Swift classes can support but Swift structs cannot :
* To develop our own custom view controller subclasses, we can inherit from another class, such as UIViewController. This cannot be achieved using Swift structs.

* Before a class is destroyed, it can be deinitialized by calling the deinit() function. This cannot be done for Swift structs.

* Structures are value types, while classes are reference types.

Value Types : When you copy a value type (for example, when it is assigned, initialised, or passed into a function), each instance preserves its own copy of the data. If you update one instance, it does not affect the other.

Reference Types : When you copy a reference type, the data is shared among all instances. The reference is copied, but the data it refers to is not. When one is altered, the other is altered as well.
A Swift literal is a direct value of a variable or a constant. It may be a number, character or string. Literals are used to initialize or assign value to variables or constants.
Different types of literals are :
* Binary Literals
* Octal Literals
* Hexadecimal Literals
* Decimal Literals
Numbers with decimal values or fractional components are called floating numbers. For example : 1.34 is a floating point number. Floating point types can represent a wider range of values than integer types. There are two signed floating point number :
Double : It represents a 64 bit floating point number. It is used when floating point values are very large.
Float : It represents a 32 bit floating point number. It is used when floating point values does not need 64 bit precision.
In Swift programming language, single-line comments are started with double slashes (//).
For example :
// This is a single line comment.  ​


Multi-line comment : Multiline comments are started with a forward-slash followed by an asterisk (/*) and end with an asterisk followed by a forward-slash (*/).
For example :
/* this is multi 
Line comment*/
There are two varieties of collection types in Swift:
Array : In Swift, you can create an array of single type or an array of multiple type.

Declare an empty array
Syntax :
let emptyIntArr:[Int] = []  

Output :



Create an array directly : Swift is a type inference language so, we can also create an array directly without specifying the data type but we have to initialise with some values so that compiler can finds out its type.
Syntax :
let someIntArr = [1, 2, 3, 4, 5]  
Output :
[1, 2, 3, 4, 5]
Dictionary : In Swift, dictionary is similar to hash table in other programing language. You can store a key-value pair in a dictionary and access the value by using the key.

Declaring an empty dictionary : To create an empty dictionary, we specify the key:value Data type inside square brackets [].
Syntax :
let emptyDictionary:[Int:String] = [:]  
Output :
Declaring a dictionary with some values
let valDictionary = ["a":10, "b":20, "c":30, "d":40, "e":50, "f":60, "g":70, "h":80, "i":90]  
Output :
["c": 30, "d": 40, "g": 70, "b": 20, "a": 10, "f": 60, "h": 80, "i": 90, "e": 50]
Inheritance is a process in which a class can inherit properties, methods and other characteristics from another class. Inheritance is supported in Swift programming language.

There are two types of classes in Inheritance in Swift :
Sub class : The class which inherits the properties from other class is called child class or sub class.
Super class : The main class from where the subclass inherits the properties is known as parent class or super class.
Floating numbers are numbers with a fractional component, like 3.25169 and -238.21.  Floating point types can represent a wider range of values than integer types. There are two signed floating point number
* Double : It represents a 64 bit floating point number, it is used when floating point values must be very large

* Float :
It represents a 32 bit floating point number, it is used when floating point values does not need 64 bit precision
A de-initializer is declared immediately before a class instance is de-allocated.  You write de-initializer with the deinit keyword.  De-initializer is written without any parenthesis, and it does not take any parameters. It is written as
deinit  {

// perform the deinitialization

Lazy stored properties are used for a property whose initial values is not calculated until the first time it is used.  You can declare a lazy stored property by writing the lazy modifier before its declaration. Lazy properties are useful when the initial value for a property is reliant on outside factors whose values are unknown.
It allows you to provide a new name to the existing data type in the programming. After declaring the alias name to the existing type, we can use it throughout the programming. It will provide more readability to the code and easy understandability.
typealias AudioS1 = UInt16
Adapter : It converts the interface of a class into other interfaces as required by the client. It covers itself around the objects to reveal a standard interface to connect with that object.
Memento : It is used in iOS as a part of the state restoration. This externalized state of the code can be store without breaching encapsulation. Memento is especially used by Apple for archiving.
@synthesize : It is used to generate a getter and setter method for the property.
@property (nonatomic, retain) NSButton *someButton1;


@synthesize someButton1;
@dynamic : It will inform the compiler that getter and setter are implemented at some other place.
@property (nonatomic, retain) IBOutlet NSButton *someButton1;


@dynamic someButton1;
let,’ and ‘var’ are used to declare the functions in JavaScript. The main difference in both of them is that ‘let’ is block-scoped, whereas ‘var’ is the functional scope. As variable is represented by ‘var,’ and it is defined in the whole program in relation to ‘let.’
Example for defining "var" :
Syntax :

var y=7;



Output : undefined 7

Example for defining "let" :
Syntax :

let x=7; console.l



Output : Error
An attribute is a construct used to provide additional information on the variable declaration and its type. It is represented with @ symbol. There are different arguments with different attributes.
Example :


It is used to shift the program control out of the scope if there is scope when one or more condition is not met. It is also called as early exit and similar to the ‘if statement’.  By using the Guard statement, we can avoid the pyramid of doom.
Example :
guard expression else {


//must contain a control statement:return, break, continue or throw.

Force unwrapping : It is the process of obtaining the value contained within an Optional. This action is risky since we are asking the compiler to extract the value and assign it to a new variable without seeing whether it is valid or not or nil.
let intNum: Int? = 1
// intSecNum have value 1.
let intSecNum: Int = intNum!
If we force unwrap an Optional item that contains nil, we get a fatalError, the application crashes, and there is no chance of recovering it.
let intNum: Int? = nil
let intSecNum= intNum! // force unwarp - fatal error
output :
fatal error: unexpectedly found nil while unwrapping an Optional value​


Implicitly unwrapped optionals : When we write an Implicitly unwrapped optional, we are defining a container that will do a force unwrap every time it is read.
var strGreet: String! = "Welcome"
/* it converts it into plain String as strGreet
automatically unwrapped it's content. */
let userName = strGreet

//assign nil
strGreet = nil
// it will throw fatal error
// fatal error: unexpectedly found nil while unwrapping an Optional value
let user2Name = strGreet​
Subscripts are used in Classes, Structures, and Enumerations to retrieve values using index from a collection, sequence, or list without invoking a method.
subscript(index: Int) -> Int {
   get {
      // subscript value declarations
   set(newValue) {
      // definitions 
Swift offers Automatic Reference Counting (ARC) to monitor and manage memory usage of our application. When class instances are no longer required, ARC automatically frees up the memory occupied by those instances.
ARC is a compiler feature that allows Objective-C objects' memory to be managed automatically. ARC analyses the lifespan needs of objects and automatically inserts proper memory management calls for programs at compile time, so users don't have to remember when to use retain, release, and autorelease.
iOS supports the SBJson framework. The SBJson framework adds more control and flexibility to the JSON handling process. It is a well designed and extremely adaptable framework that allows APIs (Application Programming Interfaces) to function in a variety of ways. SBJSON is one of the many open-source JSON parsers or generators created with Objective-C. These allow you to use JSON easily when coding Objective-C apps.
Ios Swift structs are immutable since they are of the value type. Other variables, for example, cannot modify the values of structure at any point in time. Only the "mutating" keyword is necessary to change the values of self variables within the function of the structure. Let us take the following code snippet for example:
struct demoStruct {
   var foo: String = "Initial String"
   func transformString() {
       foo = "Transformed String". 
//The above results in a compile time error: Cannot assign to property: 'self' is immutable. 
//We need to mark the method 'mutating' to make 'self' mutable.
We get a compile-time error when we try to alter the value of variable "foo" inside a function declared in the struct itself.
As a result, we will need to create a mutating function to update the value inside the structure. As a result, the correct code is:
struct demoStruct {
   var foo: String = "Initial String"
   mutating func transformString() {
       foo = "Transformed String". 
The abbreviation PLIST in ios stands for Property List. PLIST is a value and key dictionary that can be saved in our file system using the .plist file extension. The property list is used to store a smaller quantity of data in a portable and lightweight manner. In most cases, they are written in XML.
The following are examples of several sorts of property lists :
* Binary Property List
* XML Property List
Many iOS Swift functions accept multiple parameters, the last of which is a closure. Trailing closure syntax is a small amount of syntactic sugar that makes reading and writing common code easier. 
For example, consider the following code snippet :
func RunClosureAfterGreeting(name: String, closure: () -> ()) {
   print("Hi, \(name)!!!")
Instead of the above code snippet, we can write the following code (which is way cleaner than the previous one):
RunClosureAfterGreeting(name: "Danial") {
   print("The closure has been run")
GCD (Grand Central Dispatch) is a low-level API for controlling several operations at the same time. This notion is employed to aid in the enhancement of application performance. This procedure is used to handle numerous jobs at once. The most relevant API for multitasking with Async and Sync programming in iOS is Grand Central Dispatch (GCD).
Dispatch Queue : The task is managed in FIFO (First In First Out) order by the Dispatch Queue. Dispatch queues are thread-safe because they can be accessed by several threads at the same time.

Concurrent :  This process has started numerous tasks at the same time but does not know when they will finish. It can be completed in whatever sequence you want. They perform one or more things concurrently at the same time. The work is finished in the order in which it was queued, not in the order in which it was completed.

Serial : A single task will be executed at a time. It is possible to use it to synchronize access to a certain resource.

Sync : After the work is completed, a synchronous function returns control to the caller.

Asynchronous : An asynchronous function returns instantly after ordering a job to begin but does not wait for it to finish.
Generic is efficient to write sensitive and reusable functions and types. It is provided in Swift 4. Most of the people use this feature to evade the risk of duplication. 'Arrays' and 'Dictionary' are also referred to generic collection. The libraries of Swift 4 are comprised of generic code.
You can add generics to a method (function) but can’t add to a variable. Understand it with an example:
func Vector3D(x: [T], y: [T], z: [T])
 {    self.xCord = x
    self.yCord = y
    self.zCord = z}
In this example, the generic created here is in a function. You can change the T with anything you want. This is how you can add generic in function.
Delegate is a design pattern, which is used to pass the data or communication between structs or classes. Delegate allows sending a message from one object to another object when a specific event happens and is used for handling table view and collection view events.
Delegates have one to one relationship and one to one communication.
The difference between Array and NSArray are given below :
* An array can hold only one type of data, whereas NSArray can hold different types of data.
* An array is a value type, whereas NSArray is an immutable reference type.
Images, Buttons, labels, text fields, and any other elements that are visible to the user within the application are called UI elements.
Optional chaining is a useful process which we can use in combination with the optional to call the methods, properties, and subscripts on the optionals and these values may or may not be nil. In this process, we may try to retrieve a value from a chain of the optional values.
* If the optional contains a value, then calling the subscript, method or property of an optional will return a value.
* If optional is nil, then calling the subscript, method and property will return nil.
The higher-order functions are given below :
Map : Transform the array contents.
Reduce :  Reduce the values in the collection to a single value.
Sort : Sorting the arrays.
Filter : Transform the array contents.
The design patterns that are used during app development are given below :
Behavioral : Memento, and Observer.
Creational : Builder, Factory, and Singleton.
Structural :  Façade, Adapter, and Decorator.
There are seven ways to unwrap an optional in swift. They are :
Guard statement : safe.
Forced unwrapping : using “!” operator, unsafe.
Optional binding : safe.
Optional pattern : safe.
Nil coalescing operator : safe.
Implicitly unwrapped variable declaration : unsafe in many cases.
Optional chaining : safe.
NSThread : It can create a low-level thread which can be started by using the “start” method.

NSOperationQueue :
It allows a pool of threads to be created and is used to execute “NSOperations” in parallel.
Optional Binding concept is used to find out whether an optional contains a value, and it makes that value available as a variable or temporary constant. We use an optional binding concept to check if the optional contains a value or not.
Optional binding can be used with the condition (if and while) statements to check for a value inside an optional.
UIViewController class is the superclass of all the view controller objects. The functionality for presenting them, loading views, rotating them is a response to the device rotations. All the standard system behavior is provided by the UIViewController class.
MVC stands for the model view controller. MVC is a powerful software architecture pattern for using developing apps.
MVC builds on top of the Object-Oriented Programming concepts. It structures the flow of data and interaction in our app. Model-View-Controller is an important fundamental concept to be understood in iOS development. Many iOS frameworks, like UIKit, Cocoa Touch, use the MVC pattern for messaging and structured data flow.
Model-View-Controller is used to pass the data from one part of our app to another.
Its a design pattern used to assign objects in an application in any one of the three roles :
Model : Model is a wrapper of data. Model is a representation of our app data and it holds the information to a specific user like birthdate, username, etc. The model manages the application state. This also includes writing and reading data. The Model encapsulates an individual set of data and applies some logic to manipulate that data.

View : View is a representation of a UI(User Interface). A View is an object that the visible to the user and it interacts with a user interface (UI).

Controller : Controller is an intermediary between the View and the Model. The controller controls all the logic that goes between the Model and the View. Its inter-communicates messages between the Model and the View, and vice versa.
A completion handler in Swift is a function that calls back when a task completes. This is why it is also called a callback function.
A callback function is passed as an argument into another function. When this function completes running a task, it executes the callback function.
Example :
Here is a demonstrative (but not useful) example of using a completion handler in Swift:
func greet(_ completion: () -> ()) {
    print("Hello world!")
  print("Task finished.")
Output :
Hello world!
Task finished.