Search Your Question

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.

Dynamically set UITableview cell height

Ans : 

For auto cell height in tableview in Swift 3.0

Write following 2 lines of code in viewDidLoad and before reload tableview :

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44

Following steps must to do otherwise label height will not be increase and so UITableiViewCell.

Label height must be auto incremented using numberOfLines = 0

LineBreak should be set according your need word-wrap, char-wrap, etc...

ARC - Automatic Reference Counting

Ans : Automatic Reference Counting is memory management feature in iOS that provides automatic referencing counting system. According to attribute type of property like retain and release, it increment and decrements reference count at runtime.

ARC is does not handle reference cycle automatically. 

Unlike garbage collection, ARC does not handle reference cycles automatically.


Default property attributes : 

i> Memory management : strong  weak  copy  assign 
ii> Thread Safety : atomic nonatomic
iii> Mutability : readwrite readonly

@property (strong, atomic, readwrite) NSArray *name;

For IBOutlet,

@property (nonatomic, retain) IBOutlet UILabel *label;


@property (weak) IBOutlet UILabel *instructions;
In 2015, apple recommend to use Strong.


To stop retain cycle, user should mention weak reference when needed.

Q : What is retain?
A.Retain works same as Strong according to apple document. If we assign retain, it will convert to strong or consider as Strong. 

Read : Difference between Strong and Weak attribute