Search Your Question

Showing posts with label Adaps. Show all posts
Showing posts with label Adaps. Show all posts

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])
    }