Search Your Question

What are higher order functinos in swift?

Ans : Higher order functions are functions that operate on other functions by taking function as argument or returning function.

 Sorted : Sorting array. It may takes closure as argument and returns array .
let numbers : [Int] =  [1,5,2,4,3]
let arrNumbers = numbers.sorted()

By default it returns in ascending order.

numbers.sorted(by: (Int,Int) -> Bool)  - > How we want to sort array then sorted(by:)
numbers.sorted((a,b) -> Bool in return a > b } // descending order
numbers.sorted(by : >)

      Map : It iterates through the array that is calling it and changes each element of the array based on the closure passes to the method.

Use map to loop over a collection and apply the same

operation to each element in the collection. It returns after

applying transform.

let arrInt = [1,8,4,6]
I want add 1 in every number in array.
Without loop, using map,

arrInt.map( $0 + 1)  // <- This is shortest code for doing map

output : [2,9,5,7]

How map works :

The map function has a single argument which is a closure (a

function) that it calls as it loops over the collection. This

closure takes the element from the collection as an argument and

returns a result. The map function returns these results in an

array.

Another example :

let chocolateAmt = [“Dairy Milk”:20.0, “Munch”:10]

I want to increase price 5%,
so using map,
chocolateAmt.map{ (key, value) in
   value + value*0.05
      }

output : [“Dairy Milk”:21.0, “Munch”:10.5]

Another Example :

If we want index in map,

let arrInt = [1, 2, 4, 5]
let indexElement = arrInt.enumerated().map { (index,element) in
return "\(index):\(element)"
}
print(indexElement) // [“0:1”, “1:2”, “2:4”, “3:5”]

CompactMap: Use this method to receive an array of nonoptional values when your transformation produces an optional value.

let scores = ["1", "2", "three", "four", "5"]

let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.

let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out. 


FlatMapFlatmap is used to flatten a collection of collections.

Flatmap is joined word of Flat + Map. So as per name, it applies map function over collection and do flatten collection.


Test 1 :

let codes = [["abc","def","ghi"],["jkl","mno","pqr"]]
let newCodes = codes.flatMap { $0.map {$0.uppercased()} }
print(newCodes)


Output : ["ABC","DEF","GHI","JKL","MNO","PQR"] 


Test 2 :

let codes = ["abc","def","ghi"]
let newCodes = codes.flatMap { $0.uppercased() }
print(newCodes)

Output : ["A","B","C","D","E","F","G","H","I"]

-> In Test 2, first it applies map so half output is like 

["ABC","DEF","GHI"] and after that it applies flat so now full 

output is : ["A","B","C","D","E","F","G","H","I"]


Tip : 

1. String is collection from Swift 4.

2.If you do flatmap a collection containing optional values, 

flatmap will only consider the non-nil values.

let codes = [1,2,nil,3,nil,5]

let newCodesFlatMap = codes.flatMap { return $0 }
output : [1,2,3,5]


let newCodesFlatMap = codes.map { return $0 }

output : [optional(1),optional(2),nil,optional(3),nil,optional(5)]


The output of map became a collection of optional int ([Int?]) 



only because the array had nil — value in it. Otherwise it would 



have been an Int array. It is benefit of using flatMap.



Filter : Return array with elements which fulfill filter condition.           
let numbersLessThanFive = numbers.filter { (a) -> bool in return a  <  5 }
let numbersLessThanFive = numbers.filter { $0 < 5}

          Reduce : It is used to combine all element in array to make one single value.
let sumOfNumbers = numbers.reduce(0, { $0 + $1 }) 

Difference between map and flatmap : 

Big difference is Map considers nil but flatmap  remove nil value from collection.


Difference between Delegate and NSNotification

Ans :  A delegate uses protocol and creates a has-a relationship between two classes. Benefit of delegate is that we can return something back to the owning class.
Notification is like point to multi-point communication. Notification is one way  of message transmitting way.

Delegates create relationship between two classes. Notifications are used to send events to one or many classes.

We have to use delegate to specified known object. Notification for all object.

Delegate is like talking over telephone. Notification is like radio station.  

Coding of NSNotificationCenter :

[[NSNotificationCenter defaultCenter] addObjserver:self selector:@selector(useNotificationWithString:)  name:@”TimeOut” object:nil];

For BroadCast,

[[NSNotificationCenter defaultCenter] postNotificationName:@”TimeOut” object:nil userInfo:dict];

-(void) useNotificationWithString:(NSNotification *)notification
{
            dict = [notification userInfo];
}

To Remove observer,
[[NSNotificationCenter defaultCenter] removeObserver];

What is delegate?

Ans : Delegate is means of communication between objects of iOS Applications. Delegate allows one object to send message to another object when an event occurs.

i.e
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”title” message:@”message” delegate:self cancelButtonTitle:@”Ok” otherButtonTitle:nil];

Here delegate is self. So now self is responsible for handling  all event fired by this instance of UIAlertView class.

Which button of UIAlertView is clicked, for that, event is clickedButtonAtIndex is called in or by Self or currentViewController.

Create PreDefined delegate :

  1. There are two ViewController NameVC and SurNameVC.
  2.  In NameVC, there are 2 textfield named as Name and FullName and 1 button as Submit.
  3. If I write in name and click on submit, it went to SurNameVC to take Surname parameter.
  4. On SurNameVC, after write Surname, on clicking of Submit, It call delegate method and went back to NameVC and Print Full Name in FullName textfield.

Implement above delegate and protocol in Objective-C : 


I have made protocol on SurNameVC like
    @protocol SurNameVCDelegate
      -(void)setSurName:(NSString *) strSurName;
    @end
    
    @property (nonatomic, retain) id delegate;

Now on NameVC submit button click, choose delegate of  SurNameVC object as self.

   objSurNameVC.delegate = self

and create method -(void)setSurName:(NSString *) strSurName;

on NameVC and it is called from surNameVC submit button. So setSurName is delegate method. We can print fullname by concatenating Name and Surname in FullName textfield.

So we delegate just pass message from one view controller to another view controller by delegate method.

Implement delegate and protocol in Swift

I have made custom UISlider. I want to send some value from custom UISlider value changed to view controller in which it is used. So for that, I have used delegate - protocol method.

customSlider.swift  Custom Slider file


import UIKit
protocol SliderDelegate: class {
    func sliderValueChanged(_ sender : UISlider)
}


class mpgpsSlider: UIView {
     
      weak var delegateSliderDelegate?

      required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        
        let bundle = Bundle.init(for: type(of: self))
        let nib = UINib(nibName: "Slider", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        addSubview(view)
        
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for:                  .valueChanged)
    }

     @objc func sliderValueChanged(_ sender : UISlider)  {
        delegate?.sliderValueChanged(sender)
      }

}

ViewController.swift ViewController in which custom slider is used.

import UIKit

class VehicleProfileVC: BaseViewController,SliderDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        slider.delegate = self
    }
    
    func sliderValueChanged(_ sender: UISlider) {
        label.text = String(sender.value)
    }
}


Difference between Any and AnyObject

ANS : Swift has 2 types for working with  nonspecific type.
1. AnyObject
2. Any

1. AnyObject is for reference type(class) and Any is for both reference and value type.
2. AnyObject represent instance of only any class type, Any represent for any type including function type.

Note : It is always good practice to use specific type instead of Any, AnyObject.
After Swift 3.0, Objective C I'd type can be compatible with Swift Any type. Before that it is equivalent to AnyObject.
I.e
I have created dictionary in which I don't know what will be Value type.
[String : ?? ]
then ?? may be int, float, Array, Dictionary type.
So here we should use Any in replace of ??, because int, float are value type and array, dictionary are class type.
[ String : Any]

What is the nil coalescing operator in swift?

Ans : 

Swift has very powerful in terms of safety because it has feature of optional.

Optional may be has value or may be not. So we try to assign some optional to any another string or any type, then it comes some problem.

Nil Coalescing operator is solution of above problem.

let myname : String = nil
let unwrappedname = myname ?? "Default"

It checks if myname is nill then Default will be assigned to unwrappedname.
So unwrappedname is type of String instead of String?.

Such way nil Coalescing operator ?? is very useful in Swift.