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.


UIViewcontroller Lifecycle

Ans : A view controller manages set of views and making user interface. It will coordinate with data and other controller. Views are automatically loaded when view property is accessed in the app.
Following methods are used to mange view controller's view.

1. LoadView : It is automatically called when it's view property is accessed. It loads or create a view and assigned to property.

2. ViewDidLoad : It is automatically called when view controller completely loaded into memory. Override this method to perform additional initialization on views that were loaded from xib.
I.e instance variable initialization, database access, network request

Event Management to Views :

1. ViewWillAppear : It is called when View is about to added on view hierachy. If we want to change some, then we have to override this method.
Like change orientation, change screen data

2. ViewDidAppear : It is called when view was added on view's hierachy.
When we need to display loader, start UI animation ,then override this method.

3. ViewWillDisAppear : It is called when view is about to removed from hierachy. We can hide keyboard,  commit changes ,revert changes in this method by overriding.

4. ViewDidDisappear : It is called when view is removed from hierachy. We can remove cache data in this method.

Memmory Management method :
1. didReceiveMemoryWarning :
It is called automatically when system determine that the system has low amount of available memory.
Override this method remove not essential data from memory.


Ordering of excecuting methods :

1. Init(coder:)
2. (void)loadView
3. (void)viewDidLoad
4. (void)viewWillAppear
5. (void)viewDidAppear
6. (void)didReceiveMemoryWarning
7. (void)viewWillDisappear
8. (void)viewDidDisappear

What is app thining?

Ans : App thinning automatically detects the user’s device type (i.e. model name) and only downloads relevant content for the specific device. In other words, if you’re using an iPad Mini 1 (which does not have a retina display but rather a 1x resolution), then only your 1x files (more on this in a moment) will be downloaded.  The assets for more powerful and sharper iPads (such as the iPad Mini 3 or 4) will not be available for download).  Because the user needs only download the content that targets his/her specific device, this speeds up the download process and saves space on the device.

There are three aspects of app thining.

1. App Slicing : Slicing is the process of creating and delivering variants of the app bundle for different target devices. App Slicing delivers only relevant assets to each device (depending on screen resolution, architecture, etc.)  In fact, app slicing handles the majority of the app thinning process.
When you’re ready to submit the app, you upload the .IPA or .App file to iTunes Connect, as you typically would (but must use Xcode 7 as it contains the iOS 9 SDK with support for app thinning). The App Store then slices the app, creating specific variants that are distributed to each device depending on its capabilities.

2. On Demand Resources : On demand resources are files that can be downloaded after the app’s first installation.  For example, specific levels of a game (and these levels’ associated content) could be downloaded only when the player has unlocked them.  Further, earlier levels that the player has not engaged with after a certain set time can be removed to save storage on the device.
Enabling on demand resources involves changing the “Enable On Demand Resources” boolean to “Yes” in Xcode settings (under Build Settings).

3.  Bitcode : Bitcode makes apps as fast and efficient as possible on whatever device they’re running.  Bitcode automatically compiles the app for the most recent compiler and optimizes it for specific architectures. Can be turned on by the project settings under Build Settings and selecting bitcode to YES.

App thining process can be test by TestFlight software and install in various device. Size may be vary.

What is size class? Explain with Example.

Ans : 
Size Classes are groups of screen sizes that are applied to the width and height of the device screen. The two Size Classes that exist currently are Compact and Regular.

The Compact Size Class refers to a constrained space. It is denoted in Xcode as wC (Compact width) and hC (Compact height).

The Regular Size Class refers to a non-constrained space. It is denoted in Xcode as wR (Regular width) and hR (Regular height).

iPhone : Most iPhone devices will use the Compact width (wC) size class in each orientation with some exceptions.
The iPhones 6/7 Plus can inherit the Regular width (wR) size class resulting in the ability to use functionality normally reserved for the iPad, such as the split-view pane. Split-VIew pane is speciall made for iPad.

iPad : All iPad devices use the Regular width (wR) size class regardless of landscape or portrait orientation. In both horizontal and vertical landscape, the iPad will use a split-view pane to take advantage of the available screen space because it falls within this unconstrained size class.

Controlling the UI with Size Classes

In most cases, specifying the width class is sufficient when laying out your app; however, you can use the height class to customize your app as well. For example, if you use a split-view pane in an iPad app, users will see the same pane on iPhone Plus in landscape orientation because they both inherit the Regular width (wR) size class.

If that is not your intention, you can exclude a split-view pane from appearing on the 7 Plus by specifying both the width and height Size Classes. This works because the height of an iPhone Plus in landscape orientation is compact (hC) while all iPad devices have a regular height (hR).

You can also use Size Classes to target specific UI elements like font colors, font sizes, drop shadows, view colors and more to adapt to users’ device screen. These variations give you added control as to how your UI can adapt to different devices and orientations that your user may be using.




Difference between frames and bounds.

Ans : 

Frame :  View's location and size using the parent view's coordinate system
Needed while placing the view in the parent

bounds = View's location and size using its own coordinate system
Needed while placing the view's content or subviews within itself

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

So, imagine a view that has a size of  50x50 (width x height) positioned at 15,15 (x,y) of its superview. The following code prints out this view's bounds and frame:

NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
NSLog(@"bounds.size.width: %f", label.bounds.size.width);
NSLog(@"bounds.size.height: %f", label.bounds.size.height);

NSLog(@"frame.origin.x: %f", label.frame.origin.x);
NSLog(@"frame.origin.y: %f", label.frame.origin.y);
NSLog(@"frame.size.width: %f", label.frame.size.width);
NSLog(@"frame.size.height: %f", label.frame.size.height);

Output : 

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 50
bounds.size.height: 50

frame.origin.x: 15
frame.origin.y: 15
frame.size.width: 50
frame.size.height: 50

So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).

For more understanding : Visit this 


Difference between Objective-C Category and Extension

Ans : 

1.Category is a way to add methods to a class whether or not source code is available implies you can add category to foundation classes like NSString and also to your own custom classes.

2.We can add extra instance variable and property in class extension but not in Category.

3.Any variable and method inside the extension is not even accessible to inherited class.

4.Category and Extension both are basically made to handle large code base but category is a way to extend class API in multiple source file while extension is a way to add required methods out side the main interface file.

5.Use category when you have to break your same class code into different source file according to different functionality and Extension when you just need to add some required methods to existing class outside the main interface file. also when you need to modify a publicly declared instance variable in a class. for ex: readonly to readwrite you can re declare it in extension.

Read : What is Category?