Search Your Question

Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

Difference between synchronous and asynchronous calls in Objective-C

Ans : 

Synchronous :
This call means task will be executed in order.
Asynchronous : This call means task may or may not be executed in order.

When call is called synchronously, then thread that initiated that operation will be wait to current task to be finished.
When call is called asynchronously, then it will not wait.

If we want to do some task without harassing UI, we can do those tasks in background thread. This goal is to keep free main thread, so it continuously respond UI event. So we can dispatch our task in background state asynchronously.

So for do task in background thread, we will divide in 2 parts.

1. GCD - Grand Central Dispatch. By using GCD, you have to grab one of global background queue or create your own background queue.

// one of the global concurrent background queues
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// or you could create your own serial background queue:
// dispatch_queue_t queue = dispatch_queue_create("com.iosiqa.app.queuename", 0);

2. Dispatch your task to that queue asynchronously

dispatch_async(queue, ^{
    // task that to be done in background and it may be slow
});

The pattern for operation queues is very similar. Create an operation queue and add operations to that queue.

Lets see example :

Asynchronous call with Multithreading :

// Methods gets called in different thread and does not block the current thread.
[NSURLConnection sendAsynchronousRequest:request
                                   queue:queue
                       completionHandler:
    ^(NSURLResponse *response, NSData *data, NSError *error) {
}];

Synchronous call with Multithreading (not so useful):

//Do something
dispatch_sync(queue, ^{
    //Do something else // work in another queue or thread
});

//Do some more task


Difference between thread-safe and non-thread-safe in iOS

Ans : 

Thread-Unsafe -> If any object allow to modify by more than one thread at the same time.  (non-atomic property is thread-unsafe. Comments are welcomed)

Thread-safe -> If any object not allow to modify by more than one thread at the same time.Immutable objects are generally thread-safe. (atomic property attribute type. Comments are  welcomed)

In general, immutable classes like NSArray, let are thread-safe, while their mutable variants like NSMutableArray,var are thread-unsafe.



Which delegate method called when I click on push notifications?

Ans : 
Different app delegate method called depends on following scenarios

For silent notification : 

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Suspended
App state changes to Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is Not Running because killed by user
System alert is shown
No callback is called

Normal Push Notification (no content-available) :

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background or Suspended
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Not Running
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didFinishLaunchingWithOptions: then application:didReceiveRemoteNotification:fetchCompletionHandler: are both called

Query for last inserted row in SQL database

Ans. 

If column is primary key and integer, then ,

Sqlite : SELECT * FROM table ORDER BY column DESC LIMIT 1;

or

SELECT * FROM table WHERE ID = SELECT LAST_INSERT_ROWID()

FMDB : 

Last inserted id is : [fmdb lastInsertRowId];

Sqlite3 all functions : 

sqlite3_open: This function is used to create and open a database file. It accepts two parameters, where the first one is the database file name, and the second a handler to the database. If the file does not exist, then it creates it first and then it opens it, otherwise it just opens it.
sqlite3_prepare_v2: The purpose of this function is to get a SQL statement (a query) in string format, and convert it to an executable format recognisable by SQLite3.
sqlite3_step: This function actually executes a SQL statement (query) prepared with the previous function. It can be called just once for executable queries (insert, update, delete), or multiple times when retrieving data. It’s important to have in mind that it can’t be called prior to the sqlite3_preprare_v2 function.
sqlite3_column_count: This method’s name it makes it easy to understand what is about. It returns the total number of columns (fields) a contained in a table.
sqlite3_column_text: This method returns the contents of a column in text format, actually a C string (char *) value. It accepts two parameters: The first one is the query converted (compiled) to a SQLite statement, and the second one is the index of the column.
sqlite3_column_name: It returns the name of a column, and its parameters are the same to the previous function’s.
sqlite3_changes: It actually returns the number of the affected rows, after the execution of a query.
sqlite3_last_insert_rowid: It returns the last inserted row’s ID.
sqlite3_errmsg: It returns the description of a SQLite error.
sqlite3_finalize: It deletes a prepared statement from memory.

sqlite3_close: It closes an open database connection. It should be called after having finished any data exchange with the database, as it releases any reserved system resources.

UITableviewDelegate and UITableViewDataSource Methods

Ans : 

UITableview's Delegate Methods :


The UIViewController in which UITableView you use must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

Configuring Rows for the Table View

- tableView:heightForRowAtIndexPath:
- tableView:indentationLevelForRowAtIndexPath:
- tableView:willDisplayCell:forRowAtIndexPath:

Managing Accessory Views

- tableView:accessoryButtonTappedForRowWithIndexPath:
- tableView:accessoryTypeForRowWithIndexPath: Deprecated in iOS 3.0

Managing Selections

- tableView:willSelectRowAtIndexPath:
- tableView:didSelectRowAtIndexPath:
- tableView:willDeselectRowAtIndexPath:
- tableView:didDeselectRowAtIndexPath:

Modifying the Header and Footer of Sections

- tableView:viewForHeaderInSection:
- tableView:viewForFooterInSection:
- tableView:heightForHeaderInSection:
- tableView:heightForFooterInSection:

Editing Table Rows

- tableView:willBeginEditingRowAtIndexPath:
- tableView:didEndEditingRowAtIndexPath:
- tableView:editingStyleForRowAtIndexPath:
- tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
- tableView:shouldIndentWhileEditingRowAtIndexPath:

Reordering Table Rows

- tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

Copying and Pasting Row Content

- tableView:shouldShowMenuForRowAtIndexPath:
- tableView:canPerformAction:forRowAtIndexPath:withSender:
- tableView:performAction:forRowAtIndexPath:withSender: 








UITableview's Data Source Methods : The NSTableViewDataSource protocol declares the methods that an instance of NSTableView that provides the data to a table view and allows editing of the contents of its data source object.

All the methods are described in the following.

Getting Values

- numberOfRowsInTableView: (Required)
- numberOfSectionInTableView:
- cellForRowAtIndexPath : (Required)
- tableView:objectValueForTableColumn:row:

Setting Values

- tableView:setObjectValue:forTableColumn:row:

Implementing Pasteboard Support

- tableView:pasteboardWriterForRow:

Drag and Drop

- tableView:acceptDrop:row:dropOperation:
- tableView:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:
- tableView:validateDrop:proposedRow:proposedDropOperation:
- tableView:writeRowsWithIndexes:toPasteboard:
- tableView:draggingSession:willBeginAtPoint:forRowIndexes:
- tableView:updateDraggingItemsForDrag:
- tableView:draggingSession:endedAtPoint:operation:

Sorting

- tableView:sortDescriptorsDidChange:

Tips : UITableViewDelegate has no any required methods.

Difference between the atomic and nonatomic attributes?

Ans : 

Atomic property give guarantee that valid value will be return. But valid does not mean that correct value.

This also not mean that atomic property are thread safe. Different threads can attempt to read and write value at same time. So one of two value will be return - value before change or changed value.

So atomic property is suffering from performance hit due to locking and unlocking before and after get or set value.

Non atomic property has no guarantee regarding correct value, a partially correct value or may be garbage value.
This is not thread safe this enhanced speed of access property.

Atomic property lock while setting value,

While non atomic property does not lock while setting value. 

Class, Structs and Enum

Ans : 

Structs are value type, Class is reference type.
Structs are stored in stack, Class are stored in heap.

So, Structs are faster than class because of its memory management. (Read why stack allocation is more faster than heap)

Similarity between Class and Struct: 

Define properties to store values
Define methods to provide functionality
Be extended
Conform to protocols
Define intialisers
Define Subscripts to provide access to their variables

Only class can do:

Inheritance
Type casting
Define deinitialisers
Allow reference counting for multiple references.

When to use class and when to use struct?

--> When we want to maintain reference, then we should use class due to class is reference type. When not, we should use struct.

i.e 

Here's an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced.

class SomeClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance!
bClass.name = "Sue"

println(aClass.name) // "Sue"
println(bClass.name) // "Sue"

And now with a struct we see that the values are copied and each variable keeps it's own set of values. When we set the name to Sue, the Bob struct in aStruct does not get changed.

struct SomeStruct {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"

println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"

So for representing a stateful complex entity, a class is awesome. But for values that are simply a measurement or bits of related data, a struct makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.

Another theory for what to choose : 

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:
  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

Difference between Stack and Heap

Ans. 

1. Stack is used for static memory allocation, Heap is used for dynamic memory allocation.

2. Variables allocated on the stack are stored directly into memory and access memory very faster and its allocation dealt with compile time.
  Variable allocated on the heap have their memory allocated at run time and accessing their memory is bit slower.

3. Stack is always reserved in LIFO order, but you can allocate and release any element/block on heap anytime. So this is much complex to say about which block is free or allocated at given time.

4. You can use stack when you know how much data you need to allocate before compile time and they are not too big. You can use heap when you don't know how much data you need to allocate or they are too big.

5. Stack is thread specific and heap is application specific. In multi threaded, each thread has its own stack.

Stack allocation vs Heap allocation (Why stack is faster than heap)

Stack allocation means that assembly just needs to increment stack pointer and that’s it. How ever in case of heap, there is lot more going on. The memory allocator needs to ask kernel for some free page, needs to partition the page properly, with time fragmentation may occur, etc. Thus with one word to say, lot of work. Struct is stored in stack and class is stored in heap.

Which delegate method called when I click on app icon, while app is in background?

Ans :

Following methods called :

If not background : 

1. DidFInishLaunchingWithOptions

If background : 

1. application Willenterforeground
2. applicationDidBecomeActive

Tricky note : Here didFinishLaunchingWithOptions not called.

Q. Which app delegate methid called when application is to be killed?
A. applicationWillTerminate:



How to take common elements from two array in ios?

Ans. 

Swift higher order function is very useful. See below example.


let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)


Array vs Set

let array1: Array = ...
let array2: Array = ...

// Array
let commonElements = array1.filter(array2.contains)

// vs Set
let commonElements = Array(Set(array1).intersection(Set(array2)))

// or (performance wise equivalent)

let commonElements: Array = Set(array1).filter(Set(array2).contains)

Another way in Swift 4.0

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }


   print(commonItems)



Local Notification in iOS

Ans : 

Q.
 what the best way to Scheduled more than one notification but not remove the previous one?
A. Use different identifier

Different type of request access under UNAuthorizationOptions like .alert, .badge, .sound and .carplay.

let center =  UNUserNotificationCenter.current()a
center.requestAuthorization(options: [.alert, .sound, .badge]) { (result, error) in

 //handle result of request failure

}

UNNotificationRequest helps to create notification request. Which requires 3 information like an identifier, content and trigger.

1. identifier : It is unique for every notification. If we send another notification with same identifier it remove existing notification and replace it with new one.

2. content : display it in banner and main attributes are title, subtitle, body and attachment media. Using UNMutableNotificationContent we can define content.

3. trigger : the event that will trigger the notification to be displayed to the user. There are 3 classes as UNTimeIntervalNotificationTrigger,UNCalendarNotificationTrigger,UNLocationNotificationTrigger which are subclass of  UNNotificationTrigger.

example of creating local notification :

//get the notification center
let center =  UNUserNotificationCenter.current()

//create the content for the notification
let content = UNMutableNotificationContent()
content.title = " Jurassic Park"
content.subtitle = "Lunch"
content.body = "Its lunch time at the park, please join us for a dinosaur feeding"
content.sound = UNNotificationSound.default()

//notification trigger can be based on time, calendar or location
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:2.0, repeats: false)

//create request to display
let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)

//add request to notification center
center.add(request) { (error) in
    if error != nil {
        print("error \(String(describing: error))")
    }
}

-> UNUserNotificationCenterDelegate having 2 methods which is used to display notification when app is in foreground. (WillPresent delegate method is used for display notification when app in foreground).



Dynamically set UITableview cell height

Ans : 

For auto cell height in tableview in Swift 3.0

Write following 2 lines of code in viewDidLoad and before reload tableview :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

Following steps must to do otherwise label height will not be increase and so UITableiViewCell.

Label height must be auto incremented using numberOfLines = 0

LineBreak should be set according your need word-wrap, char-wrap, etc...

ARC - Automatic Reference Counting

Ans : Automatic Reference Counting is memory management feature in iOS that provides automatic referencing counting system. According to attribute type of property like retain and release, it increment and decrements reference count at runtime.

ARC is does not handle reference cycle automatically. 

Unlike garbage collection, ARC does not handle reference cycles automatically.


Default property attributes : 

i> Memory management : strong  weak  copy  assign 
ii> Thread Safety : atomic nonatomic
iii> Mutability : readwrite readonly

@property (strong, atomic, readwrite) NSArray *name;

For IBOutlet,

@property (nonatomic, retain) IBOutlet UILabel *label;


@property (weak) IBOutlet UILabel *instructions;
In 2015, apple recommend to use Strong.


To stop retain cycle, user should mention weak reference when needed.

Q : What is retain?
A.Retain works same as Strong according to apple document. If we assign retain, it will convert to strong or consider as Strong. 

Read : Difference between Strong and Weak attribute

Difference between Swift and Objective C

Ans : 

1. Swift is easier to read :

Swift removes @ symbol which exists in objective C.
Swift removes also legacy convention like semicolon at end of  statement.
Swift's method and function are easily called and [[ ]] are removed which exists in Objective C.

2. Swift is easier to maintain :

There are only 1 file to maintain name.swift. In objective c, there are .h and .m file for one viewcontroller or any views. So in swift, we have to maintain less files.

3. Swift is safe :

Optional type make the possibility of nil value very clearly, which means it generate compiler error as you write bad code instead of run time. So it reduce programmer's time due to not run the program for checking and resolve it after error coming run time.

4. Swift is robust in memory management :

ARC is available in Objective C but it supports only for Cocoa API and object oriented code. It does not support for procedural C code and Core Graphics API. So its programmer responsibility to mange memory. So it may have memory leak issue. Swift supports ARC for both procedural and object orientated code.

5. Swift less code :

+ sign concatenate two string in swift.
No need to remember value type token as %d, %s, %c like objective C. Swift does not require this type of token.

6. Swift is faster :

7. Swift supports dynamic library :

iOS doesn't support dynamic library untill released of swift and iOS 8.

8. Swift has playground :

Useful when programmar want to test 5 to 10 lines of code, he can test on playground instead of creating new application.






Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching. The Grand Central Dispatch (GCD) is a is a low-level API provided by Apple. GCD is used for managing concurrent operations. GCD has lots of benefits like

– It improves application performance and responsiveness.
– The app will become more smooth.
– Execute multiple tasks at a time or one by one as per your requirements.
GCD operates at the system level, it is managing the resources in a balanced way for all running application.



GCD & Operation Queues help keep your app user interface responsive by running slow task of main queue.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

Learn more about QOS

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

Multi threading, GCD, Operation Queue

Ans : 

1.
Thread : It is lightweight way to implement multiple paths of execution inside of an application.

2. Multi threading : iPhone CPU can only perform one operation at a time – once per clock cycle. Multi threading allows the processor to create concurrent threads it can switch between, so multiple tasks can be executed at the same time.

It appears as if the two threads are executed at the same time, because the processor switches rapidly between executing them. As a smartphone or desktop user, you don’t notice the switches because they occur so rapidly.

Multi threading allows a CPU to rapidly switch between multiple tasks in such a way that it appears as if the tasks are executed simultaneously.

You can’t update an app’s UI outside the main thread.

Race Condition  A race condition occurs when two tasks are executed concurrently, when they should be executed sequentially in order to be done correctly. You cant change view constraint while it is being calculated. So UI activity should be done in main thread so it is executed sequentially.


3. GCD : Grand Central Dispatch is a wrapper around creating threads and managing that code. Its emphasis is on dispatching.

low_level_C coding :

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // Download file or perform expensive task

    dispatch_async(dispatch_get_main_queue()) {
        // Update the UI
    }
}

Swift 3+ code :

DispatchQueue.global(qos: .userInitiated).async {
    // Download file or perform expensive task

    DispatchQueue.main.async {
        // Update the UI
    }
}

There are 4 qos - quality of service level (Priority) from higher to low :

.userInteractive,
.userInitiated,
.utility
.background.

For delaying task :

let delay = DispatchTime.now() + .seconds(60)
DispatchQueue.main.asyncAfter(deadline: delay) {
    // Dodge this!
}

4. Operation Queue : 

Operations in Swift are a powerful way to separate responsibilities over several classes while keeping track of progress and dependencies. They’re formally known as NSOperations and used in combination with the OperationQueue.

An Operation is typically responsible for a single synchronous task. It’s an abstract class and never used directly. You can make use of the system-defined BlockOperation subclass or by creating your own subclass. You can start an operation by adding it to an OperationQueue or by manually calling the start method. However, it’s highly recommended to give full responsibility to the OperationQueue to manage the state.

//Making use of the system-defined BlockOperation looks as follows:

let blockOperation = BlockOperation {
    print("Executing!")
}

let queue = OperationQueue()
queue.addOperation(blockOperation)
//And can also be done by adding the block directly on the queue:

queue.addOperation {
  print("Executing!")
}

//The given task gets added to the OperationQueue that will start the execution as soon as possible.

Different states of an operation
An operation can be in several states, depending on its current execution status.
  • Ready: It’s prepared to start
  • Executing: The task is currently running
  • Finished: Once the process is completed
  • Canceled: The task canceled


What is subclassing?

Ans : Subclassing is way of inheriting property of one class to another class. Child class inherit all behaviour of parent class. Let's talk about UIImageView.

NSObject > UIResponder > UIView > UIImageView

I have made one class as SpecialImageView which inherit UIImageView.  So SpecialImageView is subclass and UIImageView is parent class.

Suppose I want  5 imageview in my viewcontroller, which has default behaviour like borderWidth =2, broderColor = blue. 

So I have written this behaviour in SpecialImageView class once. All those 5 images are as SpecialImageView instead of UIImageView. 

So I do not need to write to all this behaviour for every 5 imageviews. So subclassing gives benefit of customisation of any class.


When we want custom UITableViewCell then we need to make subclass of UITableViewCell.

Difference between == and ===

Ans :  == checks equality and === checks identity. == check value of left side and right side are same or not. === check left side object and right side object point to same memory or not.

== used against int, float, string (value type) and === used against reference type (class type).

i.e

class SomeClass {
var a: Int;

init(_ a: Int) {
    self.a = a
}

}

var someClass1 = SomeClass(4)
var someClass2 = SomeClass(4)
someClass1 === someClass2 // false
someClass2 = someClass1
someClass1 === someClass2 // true

How to find current location?

Ans : 

Framework : MapKit
Class : CLLocationManager
Delegate : CLLocationManagerDelegate

Write NSLocationAlwaysUsageDescription and also its description in info.plist file.

Code :

@IBAction func setCurrentLocation(sender: AnyObject) {
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest

            if self.locationManager.respondsToSelector(#selector(CLLocationManager.requestAlwaysAuthorization)) {
                locationManager.requestAlwaysAuthorization() // request for authorisation for first time when app open
            } else {
                 locationManager.startUpdatingLocation()
            }
        }
    }


 //Updated location

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

//Get last updated location(current)

        let location = locations.last! as CLLocation

        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.20, longitudeDelta: 0.20))

//Set region of current location in map view with zooming

        self.mpView.setRegion(region, animated: true)

//Show current location (blue dot) on map
        self.mpView.showsUserLocation = true

    }

What is protocol? Why it is used?

Ans : Protocols are way to specify a set of methods that class has to implement if class want to work with this protocol. Protocol has 2 types of methods like Required type and Optional type methods.

1. If @required are tagged above methods, then these methods must be implemented on class which confirm this protocol.

2. If @optional are tagged above methods, then these methods is not necessary to implement on it.

Why it is used? 

Protocol provide blueprint methods for classes. It has certain methods and parameters that classes have to implement in its body. Its like that classes should have certain characteristic if it confirm protocol. Like if you want to become human(class) you must be sleep, eat, breathe(characteristics).

For more detail,
I have created Delegate and Protocol. See example.