Search Your Question

Difference between Cocoa and Cocoa Touch

And : 

Application Framework For
i) Cocoa is the application framework for Mac OS X.
ii) Cocoa Touch is the application framework for iPhone and iPod Touch.
Frameworks
i) Cocoa: Foundation and AppKit.
ii) Cocoa Touch: Foundation and UIKit
Absence of certain classes
Cocoa has NSHost and Cocoa Touch doesn't
API
i) Cocoa: All the classes used in Cocoa have the NS prefix Ex: NSTextField
ii) Cocoa Touch: classes used in Cocoa have the UI prefix Ex: UITextField
MVC patterns
i) Cocoa: Cocoa has multiple alternative design patterns – in addition to MVC
ii) Cocoa Touch: The iPhone SDK has a reinforced MVC system, which performs better than the default MVC in Cocoa
Other Differences
There Are also Differences In App Lifecycle, Sandboxing ,Memory Footprint

Difference between POP and OOP

Ans : 

POP - Protocol oriented programming
OOP - Object oriented programming

Swift has both power. POP has more advanced features having object oriented feature itself.



Base class of different class or views

Ans :

Base class of

UITableView : UIScrollView : UIView : UIResponder : NSObject
UIButton : UIControl : UIView : UIResponder : NSObject
NSObject : It is top most super class in swift. NSObject class confirm NSObject protocol.

Q : Is it compulsory to mention NSObject in swift inheritance?
A : No. Any class which is not inheriting any other class have NSObject as super class by default.


How to handle error in Swift?

Ans : 

Error Protocol is just a type for representing error values that can be thrown.

Lets declare our custom error enum by confirming Error protocol.

enum UserDetailError: Error {
        case noValidName
        case noValidAge
}

Now we make one function that throw our error type.

func userTest(age: Int, name: String) throws {
    
    guard age > 0 else {
           throw UserDetailError.noValidAge
    }
    
    guard name.count > 0 else {
           throw UserDetailError.noValidName
    }
}

In function signature, throws keyword is used and in function throw keyword is used to throw error.

Now we cal our function userTest that can throw error.

do{
       try userTest(age: -1, name: "")
}
catch UserDetailError.noValidName
{
        print("The name isn't valid")
}
catch UserDetailError.noValidAge
{
         print("The age isn't valid")
}
catch let error {
          print("Unspecified Error: \(error)")
}


Swift try, try? and try! 

  • Swift try is the most basic way of dealing with functions that can throw errors. try is only used within a do-catch block. However, try? and try! can be used without it.
  • try? is used to handle errors by converting the error into an optional value. This way if an error occurs, the function would return a nil and we known Optionals can be nil in Swift. Hence for try? you can get rid of do-catch block. 
  • try! is used to assert that the error won’t occur. Should be only used when you’re absolutely sure that the function won’t throw an error. Like try?, try! works without a do-catch block.

var t1 = try? Student(name: nil)
var t2 = try! Student(name: "Anupam")



Some truths about protocol

Q1 : Can structure confirm protocol?
A1 : Yes

Q2 : Can enumeration confirm protocol?
A2 : Yes

Q3 : Can we declare variable in protocol?
A3 : Yes -> It must be var and it must be read-Only or readAndWrite . Property declaration is like following : 

protocol someprotocol {
     var gettable : Int { get }
      var setAndGettable : Int { get set }

Q4 : Can we add function in the enumeration?
A4 : Yes

Q5 : Can protocol has own init method?
A5 : Yes

Q6 : Can protocol inherit another protocol?
A6 : Yes
protocol someprotocol : anotherprotocol {

}

Q7: Can we make a class-specific protocol?
A7: You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject or class protocol to a protocol’s inheritance list.

protocol someprotocol : AnyObject, Someanotherprotocol {
}

Now someprotocol can only be confirmed by class type. No structure or enum type can confirm this protocol.

Q8. Can we declare an optional protocol method in swift?
A8. Yes. In that protocol name and optional methods should be followed by @objc due to it consider as objective c code.

@objc protocol someprotocol {
        @objc optional func somemethod()
        @objc optional var someName : String { get set }
}

or 

We can make protocol extension and provide default body to protocol method. So any class or struct confirms that protocol doesn't require implementing that method.

Q.9 Can protocol be fileprivate?

A9. Yes. Protocol can be fileprivate, private, public. Private and fileprivate protocol can be confirmed only within current file.

Q.10 Can we define property in extension?
A10. Swift doesn’t support stored properties inside the extension. Computed property is allowed in extension.

Q.11 Can we define property in protocol?
A.11 Property in protocol must have explicit { get } or { get set } specifier. 

protocol VoiceAssistant {
        var s : String // Not allowed
        var name: String {get} // Allowed
        var voice: String {get set} // Allowed

    }

Q.12 Can we declare same name property in protocol and its extension with different datatype?
A.12 Yes. Extension declared property must have valid getter method.

protocol VoiceAssistant {
   
    var name: String {get}
    var voice: String {get set}
}

extension VoiceAssistant {
    var name: Int {get { return 5}}

}

Q.13 Can we define body in method in protocol? How?
A.13 Yes.

protocol VoiceAssistant {
    func makeMessage()
}

extension VoiceAssistant {
    func makeMessage() {
        print("Default make message method")
    }

}


How to save image in NSUserDefault?

Ans : 

NSUserDefault support format NSData for save. So convert image into NSData and then save.

Save image in NSUserDefault :

    let defaults = NSUserDefaults.standardUserDefaults()
   var imgData = UIImageJPEGRepresentation(image, 1)

   defaults.setObject(imgData, forKey: "image")


Get image from NSUserDefault :

    let defaults = NSUserDefaults.standardUserDefaults()
      if let imgData = defaults.objectForKey("image") as? NSData
      {
         if let image = UIImage(data: imgData)
           {
               self.imageView.image = image
           }

      }

What is new in Swift 5?

Ans : 

1. Abi stability : ABI stability means locking down the ABI to the point that future compiler versions can produce binaries conforming to the stable ABI. It enables binary compatibility between applications and libraries compiled with different Swift versions.

2. App thinning(smaller app size)

3. Powerful swift standard library

4. Powerful swift package manager

5. Powerfully swift compiler

Swift 5 is released with xCode 10.2. It is most powerful version till now.

What is singleton class? Pros and Cons.

Ans : The singleton pattern guarantees that only one instance of a class is instantiated. We are aware of following singleton classes,

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

Above classes are instantiate only once, if we try to create another instance, it returns also first instance. So through out application, only one instance is generated for singleton class.

Custom Singleton Class example: 

Different ways : 
1. When we need default configuration  (Using closure) : 

class NetworkManager {

    // MARK: - Properties

    private static var sharedNetworkManager: NetworkManager = {
        let networkManager = NetworkManager(baseURL: API.baseURL)
       // ....
       // Configuration
       // ....         return networkManager
    }()

    let baseURL: URL(string : "https://www.iosiqa.com")

    private init(baseURL: URL) {
        self.baseURL = baseURL
    }

    class func shared() -> NetworkManager {
        return sharedNetworkManager
    }
}

Use  : NetworkManager.shared().baseURL 

2. Using only single statement : 


class mpiosapp {
    
    static var shared = mpiosapp()
    let baseURL: URL(string : "https://www.iosiqa.com")
    private init(){}
    

}

Use : mpiosapp.shared.baseURL

Q : When static variable will be deinitialized?
A : Static variable will be deinit when program or app stops working.

Disadvantage of Singleton :

1. One of the main disadvantages of singletons is that they make unit testing very hard. They introduce global state to the application. The problem is that you cannot completely isolate classes dependent on singletons. When you are trying to test such a class, you inevitably test the Singleton as well. When unit testing, you want the class to be as loosely coupled with other classes as possible and all the dependencies of the class should be ideally provided externally (either by constructor or setters), so they can be easily mocked. Unfortunately, that is not possible with singletons as they introduce tight coupling and the class retrieves the instance on its own. But it gets even worse. The global state of stateful singletons is preserved between test cases.

2. It is static so memory will not be freeze until app will killed. It has it's own creation time and its own lifecycle.

3. Singletons create hidden dependencies. As the Singleton is readily available throughout the code base, it can be overused. Moreover, since its reference is not completely transparent while passing to different methods, it becomes difficult to track. (To solve that we should pass singleton object variable as parameter and this way is called dependency injection).



Write program of fast enumeration in swift

Ans : 


  1. enum Beverage: CaseIterable {
  2. case coffee, tea, juice
  3. }
  4. let numberOfChoices = Beverage.allCases.count
  5. print("\(numberOfChoices) beverages available")

  1. for beverage in Beverage.allCases {
  2. print(beverage)
  3. }

Write a program to convert character array to string in Swift

Ans: 

Convert character array to string :

let characterArray: [Character] = ["i", "o", "s", "i", "q", "a", ".", "c", "o", "m"]
let string = String(characterArray)

print(string)

// prints "iosiqa.com"

Convert string array to String : 

let stringArray = ["iosiqa", ".", "com"]
let characterArray = stringArray.flatMap { String.CharacterView($0) }
//let characterArray = stringArray.flatMap { $0.characters } // also works
let string = String(characterArray)

print(string)

// prints "iosiqa.com"

How many ways to pass data from one view controller to another view controller?

Ans :

Through following methods, we can pass data from one viewcontroller to another viewcontroller.

1. Using segue (PrepareForSegue) method,
2. Delegate
3. Setting variable

Let's assume we have 2 viewcontroller named VC1 and VC2. We want to pass data from VC1 to VC2 and some times VC2 to VC1. For both cases, we can use segue to pass data. But in general practise, to pass data from VC1 to VC2 (Forward data passing), we use segue and from VC2 to VC1(Backward data passing), we use protocol - delegate way.

1. Using segue (PrepareForSegue) steps :  VC1 --->  VC2


  •   Draw segue from VC1 to VC2 and give identifier string 'InputVCToDisplayVC'  to segue.
  •   Take variable in VC2.swift as :

           var fullName : String?

  •    In VC1, write following code in PrepareForSegue method,


       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "InputVCToDisplayVC"){
let displayVC = segue.destination as! DisplayViewController
displayVC.fullName = nameTextField.text
        }
        }

  •       In VC2, viewDidLoad, we can get  value of fullName and access it.
2. Using delegate steps :    VC2  --->  VC1


Import UIKit

class VC1: UIViewController, VC2Delegate {


       override func viewDidLoad() {
                super.viewDidLoad()
                
       }

       func doSomething(data : String) {
                print(data)
      }


      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if(segue.identifier == "InputVCToDisplayVC"){
      let displayVC = segue.destination as! DisplayViewController
      displayVC.delegate = self
      }
       }

 }


Import UIKit
protocol VC2Delegate {
      func doSomething(data : String) 
}

class VC2 : UIViewController {
        
      var fullName : String?
      weak var delegate : VC2Delegate?
      
      override func viewDidLoad() {
             
     }

     @IBAction func btnPassToVC1_TouchUpInside(_ sender : UIButton) {
              if let delegate = delegate {
                     delegate.doSomething(data: btn.titleLabel.text)       
              }
    }
}


In above, method we make custom protocol and create its object as delegate.We set delegate reference to VC1. So on VC2 button pressed event, VC1 doSomething method will be called.

3. Setting Variable steps :     VC1   --->  VC2

  • Take variable in VC2.swift as :  
           var fullName : String?

  • On buttonPressed action of VC1, write code as :
           let vc2 : VC2 =  UIStoryboard(name: "Main", bundle:                                                                                                        nil).instantiateViewController(withIdentifier: "VC2_ID") as! VC2
           vc2.fullName = "iOS iQA"
           self.present(vc2, animated: true, completion: nil)

Note : There are also persistent storage, by which we can store data and access that data any where in our project. But this is not correct answer or solution for above question or problem. We can store data in NSUserDefault, PList, Coredata, SQLite, KeyChain Access, File as persistent storage.






    

Write a program to remove duplicate elements from array

Ans : 


    Method - 1 : 

    extension Array where Element: Equatable {
        mutating func removeDuplicates() {
            var result = [Element]()
            for value in self {
                if !result.contains(value) {
                    result.append(value)
                }
            }
            self = result
        }
    }


   Use : 


var faa = [3, 0, 1, 0, 3, 1, 2, 0, 1, 2]
faa.removeDuplicates()

output = [3,0,1,2]


Method - 2


 let unique = Array(Set(originals))

Set is collection of unique and unordered elements. So we have converted array to set here to remove duplicate. Output array does not have same order as original.


Write a program to find first 10 prime numbers

Ans : 


     let N = 10
    let maxP = 1000
    var isPrime: [Bool] = []
    var primes: [Int] = []
    
     for i in 0...maxP {
        isPrime.append(true)
    }
    
    isPrime[0] = false
    isPrime[1] = false
    
     for i in 2...maxP {
       if isPrime[i] == true {
          var j = i*i
          while j <= maxP 
               isPrime[j] = false
               j += i
          }
          primes.append(i)
       }
    }
    
    for i in 0..<N {
        print(primes[i])
    }

Delete record from Core-data

Ans: 

Deleting a record from a persistent store involves three steps:

  1. Fetch the record that needs to be deleted
  2. Mark the record for deletion
  3. Save the changes
Code : 


let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let objects = try! context.fetch(fetchRequest) // Step 1
for obj in objects {
    context.delete(obj)  // Step 2
}

do {
    try context.save() //  <- remember to save data // Step 3
} catch {
    // Do something... 
}

Difference between Core Data and Sqlite

Ans : Core-data is not database that we understand. Sqlite is Database. 

Lets have a look over difference between Core-data and Sqlite (or Database) :

Core Data:


  1. Primary function is graph management (although reading and writing to disk is an important supporting feature).
  2. Operates on objects stored in memory (although they can be lazily loaded from disk).
  3. Works with fully-fledged objects that self-manage a lot of their behavior and can be sub classed and customized for further behaviors.
  4. Non-transactional, single threaded, single user (unless you create an entire abstraction around Core Data which provides these things).
  5. Only operates in memory.
  6. Requires a save process.
  7. Can create millions of new objects in-memory very quickly (although saving these objects will be slow).
  8. Leaves data constraints to the business logic side of the program.


Database or SQLite:


  1. Primary function is storing and fetching data.
  2. Operates on data stored on disk (or minimally and incrementally loaded).
  3. Stores "dumb" data.
  4. Can be transactional, thread-safe, multi-user.
  5. Can drop tables and edit data without loading into memory.
  6. Perpetually saved to disk (and often crash resilient).
  7. Can be slow to create millions of new rows.
  8. Offers data constraints like "unique" keys.
Credit : http://www.cocoawithlove.com/2010/02/differences-between-core-data-and.html


difference between coredata and sqlite

Advantage of Core-data : 

  • Much better memory management. With a plist you must load the entire thing into memory; with Core Data only the objects you're currently using need to be loaded. Also, once objects are loaded, they're normally placeholder "fault" objects whose property data doesn't load until you need it.
  • Related to the above, when you have changes, you can save only the changed objects, not the entire data set.
  • You can read/write your model objects directly instead of converting them to/from something like an Dictionary.
  • Built-in sorting of objects when you fetch them from the data store.
  • Rich system of predicates for searching your data set for objects of interest.
  • Relationships between entities are handled directly, as properties on the related objects. With a plist you would need to do something like store an object ID for a relationship, and then look up the related object.
  • Optional automatic validation of property values.
More about Core-data : 

  • CoreData isn't a Database. It's an object persistence layer. There is no concept of primary keys or foreign keys in CoreData.
  • If you want to establish a relationship between two entities. You'll define a relationship, CoreData takes care of how that relationship is stored.
  • Select an entity, use plus button at the bottom of the entities attributes list, select add relationship, select the destination entity from the dropdown.
  • Select the destination entity and define an inverse relationship in the same way.

What is lazy property?

Ans : 

When to use lazy initialization is when the initial value for a property is not known until after the object is initialized.

For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person.

class Person {      
  var name: String
    
  lazy var personalizedGreeting: String = {
    return "Hello, \(self.name)!"
  }()
    
  init(name: String) {
    self.name = name
  }
}

When you initialize a person, their personal greeting hasn’t been created yet:

let person = Person(name: "John Doe") // person.personalizedGreeting is nil But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:

NSLog(person.personalizedGreeting)

Bonus Tip : You do need to declare your lazy property using the var keyword, not the let keyword, because constants must always have a value before initialization completes.

Benefit of lazy property increase performance in terms of speed.

Explain defer keyword or defer statement in Swift

Ans : Defer block is executed just before return statement or exit of block. Let's have a look to following chunk of code for better understanding

      func defer()  { 
          print("Start") 
          var value: String? 
         defer { 
              if let v = value { 
                   print("Ending execution of \(v)")
              } 
        } 
      value = "defer function" 
      print("End") 
   }

So printing sequence is like following :

Start
End
Ending execution of defer function

So in short defer block will be called lastly in the current block. It will be executed in any case like before return, before the break, before throw exception. Yes, if exception comes, then also defer block will be called before program crash or going to exception.

If there is multiple defer block in same method, Then defer block will execute from down to up side.


Write a program to find missing number of array of 1 to n.

Ans : 


      import Foundation
        
        let arr = [1,2,4,5,8,6,9,7]
        let n = arr.count
        let total = ((n + 1)*(n + 2))/2
        var missingNum = total
        for item in arr {
            missingNum = missingNum - item
        }
        print(missingNum)

Write a program to distinguish lowercase and uppercase character from String in swift

Ans : 

Method 1 : 

let string = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
var output = ""

for chr in string {
    var str = String(chr)
    if str.lowercaseString != str {
        output += str
    }
}
print(output)


>>> OSQAVHWPOSI

Method 2 : 

let testString = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
let lowerCase = NSCharacterSet.lowercaseLetterCharacterSet()
let upperCase = NSCharacterSet.uppercaseLetterCharacterSet()

for currentCharacter in testString.utf16 {
  if lowerCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is lowercase.")
  } else if upperCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is UPPERCASE.")
  } else {
    println("Character code \(currentCharacter) is neither upper- nor lowercase.")
  }

}



Method 3 : 

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = CharacterSet.lowercaseLetters
let upperCase = CharacterSet.uppercaseLetters

for currentCharacter in testString.unicodeScalars {
    if lowerCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is lowercase.")
    } else if upperCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is UPPERCASE.")
    } else {
        print("Character code \(currentCharacter) is neither upper- nor lowercase.")
    }
}

Method 4 :   to identify character is uppercase or lowercase

extension Character {

        func isUpperCase() -> Bool {
            return CharacterSet.uppercaseLetters.contains(self.unicodeScalars.first!)
        }

        func isLowerCase() -> Bool {
            return CharacterSet.lowercaseLetters.contains(self.unicodeScalars.first!)
        }


  }

Write a program to reverse string in swift

Ans : 

Using Self made function : 

func reverse(_ s: String) -> String {
       var str = ""
       //.String is just like array of characters

       for character in s.characters {
            str = "\(character)" + str
            print ( str)
       }
   return str
}

print (reverse("!pleH"))


Using Swift Direct method : 

Swift 4.0

let str = "abc"

String(str.reversed())

or 

String(str.characters.reversed())



Difference between mutable array and immutable array?

Ans : 

Mutable Array content can be changed but Immutable Array content can not be changed.

You can insert, update, remove item from Mutable Array, but same is not possible in Immutable Array. There is no any methods like RemoveItem or ReplaceItem for Immutable Array, which are available for Mutable Array.

So in Immutable Array, content can not be changed after initialisation. It is either be initialised by content or by nil.

Use of Immutable array 

1. Used when we want to give array to other coder who can't be change array content.
2. Used when only fixed contents are there like array of months, days which can't be changed.

CollectionViewDelegate and CollectionViewDataSource Methods

Ans :
Popular methods is designed by blue color.

CollectionViewDelegate Methods

Managing the Selected Cells
func collectionView(UICollectionView, shouldSelectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be selected.

func collectionView(UICollectionView, didSelectItemAt: IndexPath)
Tells the delegate that the item at the specified index path was selected.

func collectionView(UICollectionView, shouldDeselectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be deselected.

func collectionView(UICollectionView, didDeselectItemAt: IndexPath)
Tells the delegate that the item at the specified path was deselected.

Managing Cell Highlighting
func collectionView(UICollectionView, shouldHighlightItemAt: IndexPath) -> Bool
Asks the delegate if the item should be highlighted during tracking.

func collectionView(UICollectionView, didHighlightItemAt: IndexPath)
Tells the delegate that the item at the specified index path was highlighted.

func collectionView(UICollectionView, didUnhighlightItemAt: IndexPath)
Tells the delegate that the highlight was removed from the item at the specified index path.

Tracking the Addition and Removal of Views
func collectionView(UICollectionView, willDisplay: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell is about to be displayed in the collection view.

func collectionView(UICollectionView, willDisplaySupplementaryView: UICollectionReusableView, forElementKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view is about to be displayed in the collection view.

func collectionView(UICollectionView, didEndDisplaying: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell was removed from the collection view.

func collectionView(UICollectionView, didEndDisplayingSupplementaryView: UICollectionReusableView, forElementOfKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view was removed from the collection view.


Handling Layout Changes
func collectionView(UICollectionView, transitionLayoutForOldLayout: UICollectionViewLayout, newLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout
Asks for the custom transition layout to use when moving between the specified layouts.

func collectionView(UICollectionView, targetContentOffsetForProposedContentOffset: CGPoint) -> CGPoint
Gives the delegate an opportunity to customize the content offset for layout changes and animated updates.

func collectionView(UICollectionView, targetIndexPathForMoveFromItemAt: IndexPath, toProposedIndexPath: IndexPath) -> IndexPath
Asks the delegate for the index path to use when moving an item.

Managing Actions for Cells
func collectionView(UICollectionView, shouldShowMenuForItemAt: IndexPath) -> Bool
Asks the delegate if an action menu should be displayed for the specified item.

func collectionView(UICollectionView, canPerformAction: Selector, forItemAt: IndexPath, withSender: Any?) -> Bool
Asks the delegate if it can perform the specified action on an item in the collection view.

func collectionView(UICollectionView, performAction: Selector, forItemAt: IndexPath, withSender: Any?)
Tells the delegate to perform the specified action on an item in the collection view.

Managing Focus in a Collection View
func collectionView(UICollectionView, canFocusItemAt: IndexPath) -> Bool
Asks the delegate whether the item at the specified index path can be focused.

func indexPathForPreferredFocusedView(in: UICollectionView) -> IndexPath?
Asks the delegate for the index path of the cell that should be focused.

func collectionView(UICollectionView, shouldUpdateFocusIn: UICollectionViewFocusUpdateContext) -> Bool
Asks the delegate whether a change in focus should occur.

func collectionView(UICollectionView, didUpdateFocusIn: UICollectionViewFocusUpdateContext, with: UIFocusAnimationCoordinator)
Tells the delegate that a focus update occurred.

Controlling the Spring-Loading Behavior
func collectionView(UICollectionView, shouldSpringLoadItemAt: IndexPath, with: UISpringLoadedInteractionContext) -> Bool
Returns a Boolean value indicating whether you want the spring-loading interaction effect displayed for the specified item.


UICollectionViewDataSource Methods


Getting Item and Section Metrics
func collectionView(UICollectionView, numberOfItemsInSection: Int) -> Int  (Required)
Asks your data source object for the number of items in the specified section.

func numberOfSections(in: UICollectionView) -> Int
Asks your data source object for the number of sections in the collection view.

Getting Views for Items
func collectionView(UICollectionView, cellForItemAt: IndexPath) -> UICollectionViewCell  (Required)
Asks your data source object for the cell that corresponds to the specified item in the collection view.

func collectionView(UICollectionView, viewForSupplementaryElementOfKind: String, at: IndexPath) -> UICollectionReusableView
Asks your data source object to provide a supplementary view to display in the collection view.

Reordering Items
func collectionView(UICollectionView, canMoveItemAt: IndexPath) -> Bool
Asks your data source object whether the specified item can be moved to another location in the collection view.

func collectionView(UICollectionView, moveItemAt: IndexPath, to: IndexPath)
Tells your data source object to move the specified item to its new location.

Configuring an Index
func indexTitles(for: UICollectionView) -> [String]?
Asks the data source to return the titles for the index items to display for the collection view.

func collectionView(UICollectionView, indexPathForIndexTitle: String, at: Int) -> IndexPath
Asks the data source to return the index path of a collection view item that corresponds to one of your index entries.

Write program for ascending sorting Int Array in any language

Ans : 
(Interviewer told syntax doesn't matter, write pseudo-code type program)

1. Not using direct function.

 void main()
    {

        int i, j, a, n, number[30];
        printf("Enter the value of N \n");
        scanf("%d", &n);

        printf("Enter the numbers \n");
        for (i = 0; i < n; ++i)
            scanf("%d", &number[i]);

        for (i = 0; i < n; ++i)
        {

            for (j = i + 1; j < n; ++j)
            {

                if (number[i] > number[j])
                {

                    a =  number[i];
                    number[i] = number[j];
                    number[j] = a;

                }

            }

        }

        printf("The numbers arranged in ascending order are given below \n");
        for (i = 0; i < n; ++i)
            printf("%d\n", number[i]);

    }

2. If we write in swift using higher order function, then

var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order

Interviewer mostly asked this question to check your programming logic. So he/she don't require syntax.

Q. Sorting strings array
A.
Method 1 : 
var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

Method 2 : 
let sortedNames = names.sort { $0.name < $1.name }
let sortedNames = names.sorted(by: <)