Swift Imtiaz Ahmad (iTechnology) - Imtiaz211/interviews GitHub Wiki

Welcome to the WikisAll wiki!

Strong and weak refrence with Example

{
     createObject()
        assignProperty()
    }
    
    func createObject() {
        person = Person(name: "Imtiaz", macbook: nil) // strong reference
        macbook = Macbook(name: "Catline", person: nil) // strong reference
        person = nil // assign nil to make reference 0
        macbook = nil // assign nil to make reference 0
    }
    func assignProperty() {
        person?.macbook = macbook
        macbook?.person = person
        person = nil
    }
}


class Person {
    let name: String
    var macbook: Macbook?
    init(name: String, macbook: Macbook?) {
        self.name = name
        self.macbook = macbook
    }
    deinit {
        print("\(name) is being deinitialization")
    }
    
    
}
class Macbook {
    let name: String
  weak var person: Person?
    init(name: String, person: Person?) {
        self.name = name
        self.person = person
    }
    deinit {
        print("Macbook name \(name) is being deinitialized")
    }
}

Print Number in blocks with odd, even and continue

func printNumbers() {
        
        let globalQueue = DispatchQueue.global()
        
        globalQueue.sync {
            for i in 1...100 where i % 2 == 0{
                print("Even \(i)")
            }
        }
        globalQueue.sync {
            for i in 1...100 where i % 2 != 0{
                print("Odd \(i)")
            }
        }
        globalQueue.sync {
            for i in 1...100 {
                print("Sequence \(i)")
            }
        }
    }

printNumber()

Generic Stack

struct Stack<Value> {
  private var elements = [Value]()
  mutating func push(_ value:Value){
   elements.append(value)
      print(elements)
  }

  mutating func pop()->Value?{
   if elements.count == 0 {
     return nil
   }
    return elements.remove(at: elements.count-1)
  }

  func peek()->Value?{
   if elements.count == 0 {
     return nil
   }
    return elements[elements.count-1]
  }

  func isEmpty()->Bool{
    return elements.count == 0
  }

  func printElements(){
    for element in elements {
       print("\(element)")
    }
 }
}

Grid Search Vertically and Horizontally

  
        let grid: [[Character]] = [["r", "y", "c", "c","a","d"],
                                   ["r", "q", "v", "d","g","j"],
                                   ["o", "p", "s", "f","q","w"],
                                   ["z", "a", "a", "r","h","b"],
                                   ["p", "w", "u", "j","k","b"],
                                   ["y", "v", "t", "s","c","t"]]
        
        print(gridCharacterSearch(grid: grid, searchParams: "cat"))
    
    
    func gridCharacterSearch(grid: [[Character]], searchParams: String) -> Bool {
        let search = Array<Character>(searchParams)
        var isPresent = false
        for i in 0..<grid.count { // Horizontally Search words
            var searchedStringHorizontally = ""
            let elements = grid[i]
            for (indx,i) in search.enumerated() {
                
                for (j, char) in elements.enumerated() where ((elements.count - j + indx) <= searchParams.count) {
                    if i == char {
                        searchedStringHorizontally.append(char)
                    }
                }
            }
            if searchedStringHorizontally == searchParams {
                print("Horizontally Present \(searchParams) in grid array")
                isPresent = true
            }
        }
        for x in 0..<grid.count { // Vertically access row
            var searchedStringVertically = ""
            var tempVerticallyArray = [Character]()
            for y in 0..<grid.count { // column
                tempVerticallyArray.append(grid[y][x])
            }
            for i in search {
                for (_, char) in tempVerticallyArray.enumerated() {
                    if i == char {
                        searchedStringVertically.append(char)
                    }
                }
            }
            if searchParams == searchedStringVertically {
                print("Vertically Present \(searchParams) in grid array")
                isPresent = true
            }
        }
        return isPresent
    }
    

Fibanocci Series

    print(fibonacciSeries(lengths: 8))
        
    func fibonacciSeries(lengths: Int) -> String {
        var term1 = 0
        var term2 = 1
        var fib = 0
        var fibString = ""
        if lengths < 3 {
            return "length is not sufficient"
        }
        fibString.append("\(term1) ")
        fibString.append("\(term2) ")
        for _ in 2...lengths {
            fib = term1 + term2
            term1 = term2
            term2 = fib
            fibString.append("\(fib) ")
        }
        return fibString
    }

Palindrome String

     let value = "radar"
        let test = Array<Character>(value)
        print(checkStringIsPalindrome(str: test))
    }
    
    func checkStringIsPalindrome(str: [Character]) -> String {
        let newCharArray = str
        let count = newCharArray.count / 2
        var flag = 0
        for i in 0..<count {
            if newCharArray[i] != newCharArray[newCharArray.count - i - 1] {
                flag = 1
            }
            break
        }
        return flag == 1 ? "Not palindrome" : "Palindrome"
    }

Reverse Array Elements

    var array = [4,3,2,8,7,6,4,9]
        print(reverseArray(array: &array))
    }
    
    func reverseArray(array: inout [Int]) -> [Int] {
        let index = (array.count) / 2
        for i in 0..<index {
            let temp = array[i]
            array[i] = array[array.count - i - 1]
            array[array.count - i - 1] = temp
        }
        return array
    }

Remove character from String

        let value = "Welcome"
        var test = Array<Character>(value)
        print(removeChars(value: &test, char: "e"))
        
    }
    func removeChars(value: inout [Character], char: Character) -> String {
        
        for (i, _) in value.enumerated() where i<value.count {
            if value[i] == char {
                value.remove(at: i)
            }
        }
        
        return String(value)
    }

Find Min and Max Number from Array

let array = [6,2,3,5,1]
        
        print(findMin(array: array))
        print(findMax(array: array))
    }
    func findMin(array: [Int]) -> Int {
        var element = array[0]
        for i in array {
            if element > i {
                element = i
            }
        }
        return element
    }
    func findMax(array: [Int]) -> Int {
        var element = array[0]
        for i in array {
            if element < i {
                element = i
            }
        }
        return element
    }

Frequency of characters in string

for (index,char) in charString.enumerated() {
            var count = 1
            let frequency = char
            If charString[index] {
            for (sunIndex, char)  in index..<charString.enumerated() {
                if frequency == char {
                    count += 1
		charString[sunIndex] = ‘\0’
                }
            } 
            print("Char: \(char) Count: \(count)")
        }
}
    }
        let name = "Imtiaz Ahmad"
        var chars = name.map { String($0)}
        for index in 0..<chars.count {
            var counter = 0
            let char = chars[index]
            print(chars[index])
            if char != "" {
                for i in 0..<chars.count {
                    let inner = chars[i]
                    if char.caseInsensitiveCompare(inner) == .orderedSame {
                        counter += 1
                        chars[i] = ""
                    }
                }
                print("Character = \(chars[index]) Occurange = \(counter)")
            }
        }

Sort Array

func sortArray(array: inout [Int]) -> [Int] {
        var element = 0
        for index in 0..<array.count {
            for item in index + 1..<array.count {
                if array[item] < array[index] {
                    element = array[index]
                    array[index] = array[item]
                    array[item] = element
                }
            }
        }
        return array
    }
var array = [1,3,5,7,2,9,33,45,21]
        print("Initial Array \(array)")
        print("sorted array \(sortArray(array: &array))")

Remove Duplicate Number from Array

        var ary = [1,2,1,3,4,6,4,5,6,5]
        DuplicateArray(array: &ary)
           
    func DuplicateArray(array: inout [Int]) {
        // Remove duplicate number from Array
        print("Original Array \(array)")
        for i in  0..<array.count where i < array.count {
            for indx in i+1..<array.count where indx < array.count {
                if array[i] == array[indx] {
                    array.remove(at: indx)
                }
            }
        }
        print("Unique Array \(array)")
    }
    }

Frequency of element in Array

 let colorArray = ["red", "green", "green", "black", "blue", "yellow", "red", "green", "yellow", "red", "red", "green", "green", "grey", "purple", "orange", "grey", "blue", "red", "green", "yellow", "orange", "purple", "black", "red", "blue","green", "blue", "orange", "white", "yellow", "blue", "red", "green", "orange", "purple", "blue", "black", "red", "red"]
        _ = mostColor(array: colorArray)
        
    }
    func mostColor(array: [String]) -> [String] {
        var topColor:[String] = []
        var colorDict:[String: Int] = [:]
        for color in array {
            if let count = colorDict[color] {
                colorDict[color] = count + 1
            } else {
                colorDict[color] = 1
            }
        }
        
        let highestValue = colorDict.values.max()
        for (color, _) in colorDict {
            if colorDict[color] == highestValue {
                topColor.append(color)
            }
        }
        return topColor
    }

Largest Number from Array

let arraySequence = [984,10,324,45,90,980]
var max = arraySequence[0]
for val in 0..<arraySequence.count {
  if arraySequence[val] > max {
  max = arraySequence[val] 
  }
}
print(max)

Second Largest Number from array

let arraySequence = [101,11,3,4,50,69,7,8,9,0] + [34,6,11]
        var second = 0
        var largest = 0
        if arraySequence[0] > arraySequence[1] {
            largest = arraySequence[0]
            second = arraySequence[1]
        } else {
            largest = arraySequence[1]
            second = arraySequence[0]
        }
        
        for ind in 2..<arraySequence.count {
            if arraySequence[ind] > largest {
                second = largest
                largest = arraySequence[ind]
            } else if ( arraySequence[ind] > second ) {
                second = arraySequence[ind]
            }
        }
        print(largest, second)

Find missing number form an sorted Array

     private func getMissingNumber(arry: [Int], n: Int ) -> Int {
        let total = n * (n + 1) / 2
        let fvar = arry.reduce(0) {$0 + $1 }
        print(fvar)
        var sum = 0
        for index in 0..<n-1 {
            sum += arry[index]
        }
        return total - sum
    }

#### How it is calling
let arry = [1,2,3,4,5,7]
        let n = arry.count / arry[0] + 1
        print(n)
        let missing = getMissingNumber(arry: arry , n: n)
        print(missing)

Power of given number

Func powerofNumber(number: Int, power: int) -> number {
var total = 1
While (power !=0) {
   total  *= number
   --power
}
Return total
}

Subscripts for class, Struct, Enum

class DaysOfWeek {
    enum MealTime {
        case BreakFast
        case Lunch
        case Dinner
    }
    var meals: [MealTime: String] = [.BreakFast : "Dosa", .Dinner : "Chapti", .Lunch : "Rice"]
}
#### How to it subscript
let monday = DaysOfWeek()
print(monday.meals[.BreakFast])

Classes have designed initializer but Struct has inbuilt designed initilizer

class Person {
    var name: String
    var age: String
    init(name: String) { // Explicitely designated initilizeer
        self.name = name
        self.age = "20"
    }
    convenience init (age: String) {
        self.init(name: "Imtiaz") // Designated initializer mandatory for conveniance
        self.age = age
    }
    required init?() { // This is called failable initilizer
        if name.isEmpty { return nil }
        self.name = "Imtiaz Ahmad"
        self.age = "20"
    }
}
struct Employee {
    var name: String // Inbuild designated initilizer
}

Static and Dynamic Dispatch

struct Person {
   func isIrritating() -> Bool { } // Static dispatch
}
extension Person {
   func canBeEasilyPissedOff() -> Bool { } // Static dispatch
}
protocol Animal {
   func isCute() -> Bool { } // Table, Dynamic Dispatch
}
extension Animal {
   func canGetAngry() -> Bool { } // Static dispatch
}

class Dog: Animal {
   func isCute() -> Bool { } // Table, Dynamic Dispatch
   @objc dynamic func hoursSleep() -> Int { } // Message Dispatch
}
extension Dog {
   func canBite() -> Bool { } // Static dispatch
   @objc func goWild() { } // Message
}
final class Employee {
   func canCode() -> Bool { } // Static dispatch
}

Visiable window

window = UIWindow.init(frame: UIScreen.main.bounds)
let navigation = UINavigationController.init(rootViewController: ViewController())
window?.rootViewController = navigation
window?.backgroundColor = UIColor.white
navigation.isNavigationBarHidden = true
window?.makeKeyAndVisible()

Get API Call

func downloadData(){
let url = NSURL(string: URL_BASE)!
var request = URLRequest(url: url as URL)
// let sessionConfiguration = URLSessionConfiguration.ephemeral
// let sessions = URLSession.init(configuration: sessionConfiguration)
request.httpMethod = "GET"
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil{
  print(error.debugDescription)
} else {
     do {
         let dic = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Dictionary<String, AnyObject>
         if let result = dic!["results"] as? [Dictionary<String, AnyObject>]{
         print(result)
           for obj in result{
             let movie = Movie(movieDict: obj)
            self.movie.append(movie)
        }

// Main UI Thread
 DispatchQueue.main.async {
    self.myCollectionView.reloadData()
 }
 }
} catch {}
}
}
 task.resume()
}

Email regex

func isValidEmail(testStr: String) -> Bool {
 let emailregEx = “[A-Z0-9a-z._%+-]+@[A-Z0-9a-z.-]+\\.[A-Za-z]{2,}”
 let emailTest = NSPredicate(format:”SELF MATCHES %@”,emailRegEx)
 return emailTest.evalute(with: testStr)
}

POST API method

func submitAction() { // POST API Working
let param = ["result":["timestamp":""]]
print(param as Dictionary)
let url = NSURL(string: "http://52.15.208.145/ecommerce/api/GetCategory")
let session = URLSession.shared
var request = URLRequest(url: url! as URL)
request.httpMethod = "POST"
Do{
  request.httpBody = try JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
 }catch let error{
 print(error.localizedDescription)
}

request.addValue("application/json", forHTTPHeaderField: "content-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else{
Return
}
guard let data = data else{
return
}
Do{
  let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
   print(json)
} catch let error {
print(error.localizedDescription)
}
}
task.resume()
}

File Manger interactor

let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let csvFile = documents?.appendingPathComponent("weather.csv")
let csvFile1 = documents?.appendingPathComponent("weather.csv").path
DispatchQueue.main.async {
if FileManager.default.fileExists(atPath: csvFile1!) {

let fileHandlers = FileHandle(forWritingAtPath: csvFile1!)
fileHandlers?.seekToEndOfFile()
fileHandlers?.write(data! as Data)
fileHandlers?.closeFile()
}

Textfield Should change range delegate

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n"{
print("Imtiaz Ahmad")
textView.resignFirstResponder()
return false
}
Else{
return true
}
}

Dependancy Injection

struct Endpoint {
    static let getEvents = "https://jsonplaceholder.typicode.com/posts"
}
class HttpClient {
    func getData(url: URL, completionHandler: @escaping (_ data: Data) -> Void) {
        URLSession.shared.dataTask(with: url) { (data, response, error)  in
            guard let data = data  else { return }
            completionHandler(data)
        }.resume()
    }
}
class Events {
//    var client: HttpClient? = nil // Property Dependancy Injector
    var client: HttpClient?
    init(client: HttpClient) { // Initializezr Dependancy Injector
        self.client = client
    }
    func getEventRecords() {
//        var client: HttpClient = HttpClient() // Hidden HttpClient dependancy
        client?.getData(url: URL(string: Endpoint.getEvents)!) { data in
            if data.count != 0 {
                print(data.count)
            }
        }
    }
}
**** calling 
var events =  Events(client: HttpClient())
        events.getEventRecords()

DispatchQueue Sequence order

 func dispatchQueue() {
        print("A")
        DispatchQueue.global(qos: .default).async {
            print("B")
            DispatchQueue.main.async {
                print("C")
            }
            print("D")
            DispatchQueue.main.async {
                print("E")
            }
            DispatchQueue.main.async {
                print("F")
                DispatchQueue.main.async {
                    print("G")
                }
            }
            print("H")
            
        }
        print("I")
    }
 ***** Output A I B D H C E F G
⚠️ **GitHub.com Fallback** ⚠️