Search Your Question

Difference between Stack and Heap

Ans. 

1. Stack is used for static memory allocation, Heap is used for dynamic memory allocation.

2. Variables allocated on the stack are stored directly into memory and access memory very faster and its allocation dealt with compile time.
  Variable allocated on the heap have their memory allocated at run time and accessing their memory is bit slower.

3. Stack is always reserved in LIFO order, but you can allocate and release any element/block on heap anytime. So this is much complex to say about which block is free or allocated at given time.

4. You can use stack when you know how much data you need to allocate before compile time and they are not too big. You can use heap when you don't know how much data you need to allocate or they are too big.

5. Stack is thread specific and heap is application specific. In multi threaded, each thread has its own stack.

Stack allocation vs Heap allocation (Why stack is faster than heap)

Stack allocation means that assembly just needs to increment stack pointer and that’s it. How ever in case of heap, there is lot more going on. The memory allocator needs to ask kernel for some free page, needs to partition the page properly, with time fragmentation may occur, etc. Thus with one word to say, lot of work. Struct is stored in stack and class is stored in heap.

Which delegate method called when I click on app icon, while app is in background?

Ans :

Following methods called :

If not background : 

1. DidFInishLaunchingWithOptions

If background : 

1. application Willenterforeground
2. applicationDidBecomeActive

Tricky note : Here didFinishLaunchingWithOptions not called.

Q. Which app delegate methid called when application is to be killed?
A. applicationWillTerminate:



How to take common elements from two array in ios?

Ans. 

Swift higher order function is very useful. See below example.


let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)


Array vs Set

let array1: Array = ...
let array2: Array = ...

// Array
let commonElements = array1.filter(array2.contains)

// vs Set
let commonElements = Array(Set(array1).intersection(Set(array2)))

// or (performance wise equivalent)

let commonElements: Array = Set(array1).filter(Set(array2).contains)

Another way in Swift 4.0

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }


   print(commonItems)



Local Notification in iOS

Ans : 

Q.
 what the best way to Scheduled more than one notification but not remove the previous one?
A. Use different identifier

Different type of request access under UNAuthorizationOptions like .alert, .badge, .sound and .carplay.

let center =  UNUserNotificationCenter.current()a
center.requestAuthorization(options: [.alert, .sound, .badge]) { (result, error) in

 //handle result of request failure

}

UNNotificationRequest helps to create notification request. Which requires 3 information like an identifier, content and trigger.

1. identifier : It is unique for every notification. If we send another notification with same identifier it remove existing notification and replace it with new one.

2. content : display it in banner and main attributes are title, subtitle, body and attachment media. Using UNMutableNotificationContent we can define content.

3. trigger : the event that will trigger the notification to be displayed to the user. There are 3 classes as UNTimeIntervalNotificationTrigger,UNCalendarNotificationTrigger,UNLocationNotificationTrigger which are subclass of  UNNotificationTrigger.

example of creating local notification :

//get the notification center
let center =  UNUserNotificationCenter.current()

//create the content for the notification
let content = UNMutableNotificationContent()
content.title = " Jurassic Park"
content.subtitle = "Lunch"
content.body = "Its lunch time at the park, please join us for a dinosaur feeding"
content.sound = UNNotificationSound.default()

//notification trigger can be based on time, calendar or location
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:2.0, repeats: false)

//create request to display
let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)

//add request to notification center
center.add(request) { (error) in
    if error != nil {
        print("error \(String(describing: error))")
    }
}

-> UNUserNotificationCenterDelegate having 2 methods which is used to display notification when app is in foreground. (WillPresent delegate method is used for display notification when app in foreground).



Optional, Optional Binding, Unwrapping and Optional Chaining

Ans : 

Optional : Optional is swift's powerful feature which come to solve problem of  non-existing value. It is just a type . There are two types as Int (which must has a value) and Int?(which may contain a Int value or may have nil value). It is declared as T? i.e Int?, String?

Forced Unwrapping : Exclamation mark ( ! ) is used to unwrap value.
i.e let optionalInt : Int? = 5
let intVal : Int = 2
optionalInt! + intVal

So we hvae forecfully unwrap optionaInt. That means we tell compiler that optionalInt has a value and extract and use it.

But this is not good practise. If sometimes optionaInt has not value and we try to unwrap, then app will be crashed. A good practise is to check with nil before unwrapping or use optional binding. It checks it has value or not and if and only if it has value extract it and use it.

Optional Binding : You use optional binding to check if the optional contains a value or not. If it does contain a value, unwrap it and put it into a temporary constant or variable.

Example :

var stockCode:String? = findStockCode("Facebook")

let text = "Stock Code - "

if let tempStockCode = stockCode {

    let message = text + tempStockCode

    println(message)
}

The “if let” (or “if var”) are the two keywords of optional binding. In plain English, the code says “If stockCode contains a value, unwrap it, set its value to tempStockCode and execute the conditional block. Otherwise, just skip it the block”. As the tempStockCode is a new constant, you no longer need to use the ! suffix to access its value.

Implicitly Unwrapped Optional : When we are very very sure about it has value after first time it is set, then we need not unwrap every time. So for this type of scenario, we have to use it with ! mark in their type.

// forced unwrapping
let optionalInt: Int? = 123
let forcedInt: Int = optionalInt!

// implicitly unwrapped optional
let assumedInt: Int! = 123
let implicitInt: Int = assumedInt

It may has nil value.

Optional Chaining :

The feature allows us to chain multiple optionals together with the “?.” operator.


if let sharePrice = findStockCode("Apple")?.price {

    let totalCost = sharePrice * 100

    println(totalCost)

}

FindstockCode method returns optional value. We can access multiple optional together using Optional chaining feature.