Search Your Question

What is protocol extension? Why Swift called as Protocol Oriented Language?

Ans : It is same as we extend class to add functions to existing class. Here we can add functions to existing protocol by extending protocol.

protocol proto {
   func add()
}

extension proto {
   func sub()

}

Benefits :

1.

We can also add default body to protocol extension function. So any type which confirm protocol has choice to implement that method or not. In other words we can say that it become optional method. Protocol extension method must have body.

protocol proto {
    func add()
}

extension proto {
    func add()  {
        print("add method called")
    }
    
    func sub() { }
}

class cp : proto {
   
}

let pq = cp()
pq.add()



Output : 
add method called

2. 

We can confirm multiple protocol and we can say that is multiple inheritance.

protocol proto1 {
    func add()
}

protocol proto2 {
    func sub()
}

class cp : proto1,proto2 {
    func add() {
        
    }
    
    func sub() {
        
    }
}

let pq = cp()
pq.add()

3. 

We can make protocol comparable due to protocol extension.

protocol Score: Comparable {
  var value: Int { get }
}

struct RacingScore: Score {
  let value: Int
  
  static func <(lhs: RacingScore, rhs: RacingScore) -> Bool {
    lhs.value < rhs.value
  }

}

4.

Mutating function in protocol to change value of protocol.

Struct is value type. You can only change property of struct only if property declared as var and instance is also var.



So, if we add mutating before func, it allow to change value in struct type. Same thing also can be done with protocol and protocol extension.

5.

There's also obviously anything that you can do with generics in Swift that couldn't be done in Objective C.  So for instance the Indexable protocol could be extended to have a function that returned the index range length which might only apply if the index is an Int like this:

extension Collection where Self.Index == Int
{
  func length () -> Int
  {
     return endIndex - startIndex
  }

}


Due to this very powerful features of protocol in Swift, Swift is called Protocol Oriented  Programming Language.


What is accuracy of GPS location?

Ans : 

CLLocationAccuracy class provides accuracy constant.

kCLLocationAccuracyKilometer:
Accurate to the nearest kilometer.


kCLLocationAccuracyBestForNavigation:
The highest possible accuracy that uses additional sensor data to facilitate navigation apps. 
kCLLocationAccuracyBest:
The best level of accuracy available.
kCLLocationAccuracyNearestTenMeters:
Accurate to within ten meters of the desired target. 
kCLLocationAccuracyHundredMeters:
Accurate to within one hundred meters.
kCLLocationAccuracyThreeKilometers:
Accurate to the nearest three kilometres.



What is UIResponder Chain?

Ans : 

Apps receive and handle events using responder objects. A responder object is any instance of the UIResponder class, and common subclasses include UIView, UIViewController, and UIApplication. UIKit manages most responder-related behavior automatically, including how events are delivered from one responder to the next.

Example : 

For every event, UIKit designates a first responder and sends the event to that object first. The first responder varies based on the type of event. 

UIKit uses view-based hit testing to determine where touch events occur. Specifically, UIKit compares the touch location to the bounds of view objects in the view hierarchy. The hitTest:withEvent: method of UIViewwalks the view hierarchy, looking for the deepest subview that contains the specified touch. That view becomes the first responder for the touch event. 

If a touch location is outside of a view’s bounds, the hitTest:withEvent: method ignores that view and all of its subviews. As a result, when a view’s clipsToBounds property is NO, subviews outside of that view’s bounds are not returned even if they happen to contain the touch.

UIResponder Chain
  • If the view is the root view of a view controller, the next responder is the view controller. 
  • If the view is not the root view of a view controller, the next responder is the view’s superview. 
  • If the view controller’s view is the root view of a window, the next responder is the window object. 
  • If the view controller was presented by another view controller, the next responder is the presenting view controller. 
  • UIWindow. The window’s next responder is the application object. 
  • UIApplication. The app object’s next responder is the app delegate, but only if the app delegate is an instance of UIResponder and is not a view, view controller, or the app object itself.

What is capture and capture list in closure?

Ans :

According to apple document :

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. 

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

Closure is reference type

Capturelist is used to stop memory leakage.

Code for Example of memory leakage :


class Increment {
    var number = 0

     deinit {
        print(#function)
    }
    
    lazy var incrementNumber: (Int) -> () = { value in
        self.number += value
        print(self.number)
    }
}

 do {
  let increment = Increment()

  increment.incrementNumber(3
 }


This will cause memory leak, the closure refers back to the object itself, it refers to self in order to increment the number, and that will create a reference cycle:

We have an object and the object has a stored property that refers to a closure.
That closure refers back to self (means Increment instance)

In above example, deinit should be called. But it never due to retain cycle created.

To Stop memory leakage we use capture list :

1. [unowned self]
2. [weak self]
3. [strong self] - Default

1.

lazy var incrementNumber: (Int) -> () = { [unowned self] value in
        self.number += value
        print(self.number)
    }

If I use [unowned self] there here less chance to crash. But if we use
let increment = Increment().incrementNumber(3)
then there will be more chance to be crashed. We can not immediately call incrementNumber method after object instantiated. Because when the stored property has returned, the object (increment instance) can be deallocated, nothing else is referring to it.

2.

 let’s change [unowned self] to [weak self], that means that everywhere that self is accessed, we treat it as a weak property. While using weak, we should use optional self? to access property.

When the stored property has returned, if the object be deallocated, mean self is nil, then the number will not be incremented. This code will make it easy to handle if self is nil

So when no clue to what to use, we should use [weak self] as capture list.





What is AutoReleasePool?

Ans : 

In simple word, it is pool contained objects that will be released in some time.

Object's retain and release is constant action on object. For that Retain() and Release() methods called in objective c to control memory flow. As iOS objects work on retain count concept, it tells retain counts and it will be released if it reaches to 0.

Sometimes, we can not continuously use Release() method to release object.

Code for example :

 -(NSString *)getCoolLabel {
    NSString *label = [[NSString alloc] initWithString:@"SwiftRocks"];
    [label release];
    return label;
 }

    

Here label has 2 retain count and after return it has 1 retain count. It will be in memory as we can not execute release after return label; statement.

So solution :
return [label autorelease];
It will not release label instantly, but it inserts label in pool, and in some time, when autorelease pool thread execute, it

Note : Instead of instantly reducing the retain count of an object, autorelease() adds the object to a pool of objects that need to be released sometime in the future, but not now. By default, the pool will release these objects at the end of the run loop of the thread being executed, which is more than enough time to cover all usages of getCoolLabel() without causing memory leaks.

Whatever code that takes much memory we can add in autoreleasepool block.
I.e

@autoreleasepool {
           NSString *contents = [self getFileContents:files[i]];
           NSString *emojified = [contents emojified];
           [self writeContents:contents toFile:files[i]];

       }

Above all code written in objective - c, but in swift AutoReleasePool is required?

Yes, it depends on code.  It’s a different story if your code is dealing with legacy Obj-C code, specially old Foundation classes in iOS.

To put it short, autoreleasepool is still useful in iOS/Swift development as there are still legacy Obj-C classes in UIKit and Foundation that call autorelease, but we not have to worry where there is pure swift code.



What is Generics in Swift? Write a program to make and use generics.

Ans :

Apple doc says: Generic code enables you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication by using generics in most cases.

Code for Example :


 let intArray = [1,2,3,4,5] // type int
 let stringArray = [“abhi”, “iOS”] // type string



If we want to print all values, we have to make 2 functions accepting integer array or string array.
But using Generic, we can make 1 method accepting generic type.



 func printAnyArray<T>(arr:[T]) {
       arr.map { print($0) }

 }


 <T> after the function name represents a generic function. A generic function can work with whatever type. We can put whatever instead of T. T is placeholder type. We can use for dictionary like Dictionary<key,value> and for array like Array<element> .

Generic function with parameter type : 


//Declare
func anotherMethod<T, U> (first: T, second: U) { print("first one called")}
func anotherMethod<T> (first: T, second: T) { print("second one called")}
//Call
anotherMethod(first: 123, second: "456"// T - Int, U - String
anotherMethod(first: 123, second: 456// T - Int




In above methods, we use different placeholder type in method1 and same placeholder type in method2. If out passing parameter types are different then 2nd method will be called, and if same then 1st method will be called.

Generic function with type constraints :


func middleVal<T>(array: [T]) -> T? {
  guard !array.isEmpty else { return nil }
  return array.sorted()[(array.count - 1) / 2]
}

   

Sometimes, we require specific types only i.e type which confirm comparable protocol


func middleVal<T: Comparable>(array: [T]) -> T? {
  guard !array.isEmpty else { return nil }
  return array.sorted()[(array.count - 1) / 2]
}

    

Above method will only accepts. int, float, double.


If you have any comment, question, or recommendation, feel free to post them in the comment section below!  

What is callback function?

Ans : A callback function is a function that is passed as an argument to another function, to be “called back” at a later time.

Code for Example :


func printValue(index: Int, element: Int) {
    print("index = \(index), Element = \(element)")
}
func each(array: [Int], callback: (Int, Int) -> Void) {
    for i in 0..<array.count {
        callback(i, array[i])
    }
}

each(array: [1, 2, 3, 4, 5],callback: printValue)


Here each function type is ( [Int], (Int, Int) -> Void ) .
Here callback function type is ( (Int, Int) -> Void ) .

Callback function mostly used when we want to pass block of code that should be executed in another function execution complete.

What are best approach to implement if large data is coming from core data and show data on tableview?

Ans : 

Use NSFetchResultsController : A controller that you use to manage the results of a Core Data fetch request and to display data to the user.


If we have very large data in database and we want all data to show in tableview, then we have to write some extra code on core data fetch request as fetching data will stuck UI.
Then we can use NSFetchResultsController as it has ability to fetch data from memory in batches. So data coming in batch when we scroll tableview and saved in cache.

We have to make property of type NSFetchResultsController :

- (NSFetchedResultsController *)fetchedResultsController {
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
        entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
        initWithKey:@"details.closeDate" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
    
    [fetchRequest setFetchBatchSize:20];
    
    NSFetchedResultsController *theFetchedResultsController =
        [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
            managedObjectContext:managedObjectContext sectionNameKeyPath:nil
            cacheName:@"Root"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
    
}


and in ViewDidLoad :

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSError *error;
 if (![[self fetchedResultsController] performFetch:&error]) {
  // Update to handle the error appropriately.
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  exit(-1);  // Fail
 }
    
    self.title = @"Failed Banks";
    
}


We get data in numberOfRowInSection :
id  sectionInfo =
        [[_fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];

We get data in cellForRowAtIndexPath :
FailedBankInfo *info = [_fetchedResultsController objectAtIndexPath:indexPath];

We also have to write FetchResultsControllerDelegate methods as it is as at apple provide at end of ViewController's code.

Enjoy lazy loading data...

Tutorial : Ray Wanderlich


How you can add column in entity in core data that can be also added in next release?

Ans : When you initialise a Core Data stack, one of the steps involved is adding a store to the persistent store coordinator. When you encounter this step, Core Data does a few things prior to adding the store to the coordinator. First, Core Data analyzes the store’s model version. Next, it compares this version to the coordinator’s configured data model. If the store’s model version and the coordinator’s model version don’t match, Core Data will perform a migration, when enabled.

Note: If migrations aren’t enabled, and the store is incompatible with the model, Core Data will simply not attach the store to the coordinator and specify an error with an appropriate reason code.

Migrations happen in three steps:
  1. Core Data copies over all the objects from one data store to the next. 
  2. Core Data connects and relates all the objects according to the relationship mapping. 
  3. Enforce any data validations in the destination model. Core Data disables destination model validations during the data copy.
Database Migration : 

Lightweight Migration
Manual Migration
Custom Manual Migration
Fully Manual Migration

Setting for Lightweight Migration: 

NSMigratePersistentStoresAutomaticallyOption: true
NSInferMappingModelAutomaticallyOption: true


Coredata Migration Tutorial : RayWanderLich


What is Core Data Stacks?

Ans : Core Data is Apple’s object graph management and persistency framework.

Core Data Stack
Core Data Stack


  1. Managed Object
  2. Managed Object Context
  3. Managed Object Model
  4. Persistent Store Coordinator

  1. NSManagedObject’s are the model objects exposed by Core Data.
  2. NSManagedObjectModel is a database schema that describes the application’s entities. It defines the structure of the managed objects.
  3. NSPersistentStoreCoordinator associates persistent storage and managed object model. It lends itself to mapping the data from the storage, say SQLite data base rows, into the object model. It is a task of high complexity and is often taken for granted when working with Core Data.What is more, the persistent coordinator is used by the managed object context when it comes to saving or fetching objects.
  4. NSManagedObjectContext controls the life cycle of the managed objects and provides operations to create, save and fetch them. You can think of the managed object context as a scratch pad with a group of managed objects.

Starting from iOS 10, NSPersistentContainer is responsible for creation and management of the Core Data stack.
NSPersistentContainer exposes a managed object model, a managed object context and a persistent store coordinator as well as provides many convenience methods when working them, especially when it comes to multithreaded applications.