Swift Interview Questions and Answers

Question 10. What is a In – Out parameter

Answer 10. In-Out parameters are passes by reference and when they are changed the change is reflected in actual value.In – out keyword allows the function parameters to be changed and the changes persist after the function execution has ended.

Only variables can be passes constant and literals cannot be passed as inout parameter.

var a = 3
var b = 4


func incrementByFive(_ a:inout Int , _ b:inout Int){
  a = a + 5 
  b = b + 5
}

// function can be called as

incrementByFive(&a,&b)  // notice the &

print("value of a: \(a)")//prints "value of a : 8"
print("value of b: \(b)")//prints "value of a : 9"

Question 11. What are convenience initializer and designated initializer?

Answer 11. Designated initializer are primary intializer of any class and they ensure that all properties of the class are initialized before a call to super class intializer is made.

Convenience initializers are support initializers which are used to provide a used based init method.They are declared with  convenience  key word

// designated intializer

init(sender:String,quantity:Int){
  self.sender = sender
  self.quantity = quantity
  super.init()   // super .init() will result in compile time error if any of sender and quantity properties are not intialized
}

convenience init(sender:String){  //made a easy to call init method
  self.init(sender,4)  //passed a default value of quantity to designated initializer if user does not provide it
}

Here we saved the burden of passing quantity at intialization when it is not required. This allows for creating multiple init methods with only necessary parameters.

So the basic rule of convenience initializer implementation as described in Aplle doc for swift language guide is

Rule 1

A designated initializer must call a designated initializer from its immediate superclass.

Rule 2

A convenience initializer must call another initializer from the same class.

Rule 3

A convenience initializer must ultimately call a designated initializer.

A pat on the back !!