Search Your Question

What is extension and How to use it?

Ans :
Swift Extension :

Add a new swift file with File > New > File... > iOS > Source > Swift File, but you can call them what you want.
The general naming convention is to call it TypeName+NewFunctionality.swift

Make extension of Double

Double+Conversions.swift

import Swift // or Foundation

extension Double {

    func celToFahren() -> Double {
        return self * 9 / 5 + 32
    }

    func fahrenToCel() -> Double {
        return (self - 32) * 5 / 9
    }
}

How to make extension:

let boilingPointCel = 100.0
let boilingPointFaren = boilingPointCel.celToFahren()
print(boilingPointFaren) // 212.0

Make extension of UIColor

UIColor+CustomColor.swift

import UIKit

extension UIColor {

    class var customGreen: UIColor {
        let darkGreen = 0x008110
        return UIColor.rgb(fromHex: darkGreen)
    }

    class func rgb(fromHex: Int) -> UIColor {

        let red =   CGFloat((fromHex & 0xFF0000) >> 16) / 0xFF
        let green = CGFloat((fromHex & 0x00FF00) >> 8) / 0xFF
        let blue =  CGFloat(fromHex & 0x0000FF) / 0xFF
        let alpha = CGFloat(1.0)

        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }

}
See here also.

Using extension :

view.backgroundColor = UIColor.customGreen

Summary : Once you define an extension it can be used anywhere in your app just like the built in class functions. In Objective-C extensions are known as categories.

Objective C Extension : 

In objective c, when you want to make behavior of some property private you use class extension.
-> it comes with .m file only.
-> mainly for properties.
The implementation of the extension must be in the main @implementation block of the file.
Extension can only be added to the classes whose source code is available because compiler compile the source code and extension at same time.

Difference between Delegate and Datasource

Ans :

A delegate type object responds to actions that another object takes.
i.e  the UITableViewDelegate protocol has methods such as didSelectRowAtIndexPath for performing actions upon a user selecting a particular row in a table and willDisplayCell which called before delegate use cell to draw row.

DataSource type object gives data to another object.
i.e UITableViewDataSource protocol has methods such as cellForRowAtIndexPath and numberOfSectionInTaboeView dictating what should be displayed in the table.

Understanding Delegate in More Detail : 

If Object X call Object Y to perform an action. Object X should know when Object Y complete task and take action after that. 

Here we can tell that X is delegate object of Y. Y will have a reference of X. So X will implement delegate methods of Y. So Y can notify to X via delegate method.

One more point we can say that Delegate about controlling of UI and DataSource about controlling data.

Buy CHRYOSOLITE Superman Fan Art Men's Round Neck TShirt

Difference between Sqlite and CoreData

Ans  : Sqlite is database and Coredata is Object Relational Model which is layer between UI and Database. Coredata is memory efficient and Querying to Sqlite is not so efficient.
So we can't compare Sqlite and Coredata. Both are different thing.


What are persistent storage in iOS and Which one is most secure?

Ans : There are SIX types of persistent storage.

1. Userdefaut
2. Property List
3. Sqlite
4. Keychain
5. Files
6. Coredata

If brief answer they asked then follow :

1. Userdefaut : NSUserDefault class allow us to store small amount of data. It can store NSData, NSString, NSArray, NSDictionary,  NSNumber,
The maximum data can we saved depends on iOS. Currently it can store 4GB of data.
But if file is too large, then it takes too much time for retrieve and write data in file. So we can save small amount of data only. Otherwise it waste time.
We can also store our custom objects in userDefaults. We achieve this by conforming our class to NSCoding protocol. We can then convert our custom object into NSData with the help of NSKeyArchiver class. The NSData is then stored into userDefaults like other objects. Similarly we can get NSData from userDefaults and then using NSKeyUnarchiver convert the NSData back to our custom objects.

2. Property List : As userdefaut save data in plist file, so like userdefaut, Property List is not also made for save large amount of data. There is one method of NSArray and NSDictionary as writeToFile for saving data.

3. Sqlite : If your application deals with large amount of data with relationship then we should use sqlite. It's API is written in C language and embedded with our application so it is very fast. There are ORM for bringing gap between obj c app and sqlite like, FMDB,  Realm

4. Keychain : If you want to save highly sensitive and secure data like passwords and secret codes then there is a good news for you. Storing data in keychain is most secure way. To store data, I have taken library named SwiftKeyChainWrapper from cocoapods.

To Save data in Keychain : 

let saveSuccessful: Bool = KeychainWrapper.standard.set("Some String", forKey: "myKey")

To get data from Keychain :

let retrievedPassword: String? = KeychainWrapper.standard.string(forKey: "userPassword")

To remove data from keychain : 

let removeSuccessful: Bool = KeychainWrapper.standard.remove(key: "myKey")

5. Files : You can save data to any type of file. There are three type of folder like Document, Library, Tmp fo saving various type of file.

6. Core Data : Apple’s solution for persistence allows applications to persist data of any form and retrieve it. It  isn’t technically a database, although it usually stores its data in one (an SQLite DB). It’s not an object-relational mapper (ORM), though it can feel like one. It’s truly an object graph, allowing you to create, store, and retrieve objects that have attributes and relationships to other objects. Its simplicity and power allow you to persist data of any form, from basic data models to complex.

I have written for loop from 1 to 10. But when i=7 then then it comes out from loop. I have not written any specific keyword nor exception generated. How it is possible?

ANS :

for(int i=0, i<10:i++)
{
     if(i==6)
          {
              i=10;
           }
}
Here I am trying to iterate from 0 to 9. This loop is iterating till Condition i<10 matches.
Now in iterating, when loop comes i=6 I will make i=10.
So in next iteration, i<10 condition is mismatched. So it comes out from loop.
There is no any keyword used or any exception generated.

Bonus Tip : You can run swift code online here


What is StackView? What is advantage and distribution type of stackview?

Ans : Stack View allows to layout views in a stack in either horizontal or vertical fashion. In Xcode-7, stackview is introduced.

Advantage : Stacks are containers that keep views aligned automatically.

Distribution Types :

Fill(Default) : When you place your controls inside a UIStackView with Fill set as the distribution, it will keep all but one of the controls at their natural size and stretch one of them to fill the space. It determines which control to stretch by noting which one has the lowest Content Hugging Priority (CHP).

Fill Equally : With this type, each control in a UIStackView will be of equal size. All of the space between the controls will be used up, if possible. I added a spacing of eight between the UITextFields, so again you could see the size of each one. With this type, the CHP does not matter, because each control is the same size.

Fill Proportionally : The UIStackView will ensure the controls maintain the same proportion relative to one another as your layout grows and shrinks. Unlike the previous two settings, the Fill Proportionally distribution needs the controls to have an intrinsic content size. The Fill and Fill Equally distribution tell their child controls how big they should be, but this one is the other way around (as long as there is enough space for all of your controls to be their natural size). The proportions for the images and labels are maintained for the different layout sizes.

Equal Spacing : This distribution type will maintain an equal spacing between each of the controls and will not resize the controls themselves.

Equal Centring :  It will equally space the centres of the controls. Space between every control is equal.


What is inout parameter in swift?

 Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

func add(x: Int, y: Int) -> Int
{
x=7              error: Can not assign to value x, x is let constant
return(x+y)
}

func add(x: inout Int, y: Int) -> Int
{
x=7           
return(x+y)
}

Bonus Tip : You can run swift code online here
  

Collectionview or Scrollview or PageViewController, Which one is most preferable?

It depends on requirement. If too many pages or items, then Collectionview or pageviewcontroller is good option. Because Collectionview can reuse cell for display view, whereas PageViewController load only current page,previous page and next page in memory. As Scrollview loads all subviews in memory, it will consume too much memory.

Pageviewcontroller load multiple viewcontroller in memory. So preferable most in following order :

1. UICollectionview
2. UIPageViewController
3. UIScrollView


UITableview and UICollectionview

Similarity :
The way to setup both with cell registration, dequeing cells, specifying size and heights are pretty much the same.

Diffrence :
1. The collection view is much more robust in terms of layout features and other things like animations.
Tableiw is a simple list, which displays single-dimensional rows of data. It’s smooth because of cell reuse and other magic.

2. UICollectionView is the model for displaying multidimensional data . 
UITableViewhas a couple of styles of cells stacked one over the other. You should not try to bend it to do any other kind of things too much complex than that kind of layout.

3. UICollectionView is a much more powerful set of classes that allow modifying almost every aspect of how your data will appear on the screen, especially its layout but also other things.

Advantage of Collectionview :
The biggest advantage of using collection view is the ability to scroll horizontally.
 If you want multiple columns in your apps then UICollectionView is the best way to do it. 


It is possible to have multiple columns in table view as well but it gets really messy since you are dealing with and array to display data in a table view.

UICollectionView Supports complex layouts. Apple provides you with something called UICollectionViewDelegateFlowLayout which provides you the flow of left and right as well as up and down.

UICollectionView supports custom animations based on different layouts which again cannot be done in UITableView.

Disadvantage of Collectionview (Advantage of Tablvieview over) :

Major disadvantages of using UICollectionView is auto sizing of your cells. It takes a lot of trial and error to get auto sizing to work correctly. UITableView wins here as all you have to do is return UITableView automatic dimensions for the height of your row in each one of your cells.

Summary :
If you need more control over your layout, go with UICollectionView, If you need simple list go with UITableview.