Search Your Question

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... 
}