Search Your Question

Application States

Ans : 

Before iOS 4.0 there were 3 states. Not running, inactive and active.

  1. Non-running - The app is not running.
  2. Inactive - The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received.
  3. Active - The app is running in the foreground, and receiving events.
  4. Background - The app is running in the background, and executing code.
  5. Suspended - The app is in the background, but no code is being executed.
For maintaining above states, there are following app delegate methods:


application:willFinishLaunchingWithOptions (First method)
Method called when the launch process is initiated. This is the first opportunity to execute any code within the app.

application:didFinishLaunchingWithOptions
Method called when the launch process is nearly complete. Since this method is called is before any of the app's windows are displayed, it is the last opportunity to prepare the interface and make any final adjustments.

applicationDidBecomeActive
Once the application has become active, the application delegate will receive a callback notification message via the method applicationDidBecomeActive.

This method is also called each time the app returns to an active state from a previous switch to inactive from a resulting phone call or SMS.

applicationWillResignActive
 Each time a temporary event, such as a phone call, happens this method gets called. It is also important to note that "quitting" an iOS app does not terminate the processes, but rather moves the app to the background.

applicationDidEnterBackground
This method is called when an iOS app is running, but no longer in the foreground. In other words, the user interface is not currently being displayed. According to Apple's UIApplicationDelegate Protocol Reference, the app has approximately five seconds to perform tasks and return. If the method does not return within five seconds, the application is terminated.

applicationWillEnterForeground
This method is called as an app is preparing to move from the background to the foreground. The app, however, is not moved into an active state without the applicationDidBecomeActive method being called. This method gives a developer the opportunity to re-establish the settings of the previous running state before the app becomes active.

applicationWillTerminate
This method notifies your application delegate when a termination event has been triggered. Hitting the home button no longer quits the application. Force quitting the iOS app, or shutting down the device triggers the applicationWillTerminate method. This is the opportunity to save the application configuration, settings, and user preferences.



What is localization?

Ans : 

Localization is simply the process of translating your app into multiple languages. However, before you can localize your app, you first need to internationalize it. Internationalization is the process of making your app able to adapt to different languages, regions, and culture. Simple enough, I guess.

So after opening app, we can detect user's locale and change app's language,time accordingly.


Difference Between Inheritance And Extensions?

Ans : 

When to use extension : 
Are you adding general-purpose functionalities that should be available to every UITextField? If so, make an extension. All UITextField instances can call the new methods.

When to use inheritance : 
Are you adding functionality that should be restricted to special instances of UITextField that you would identify precisely? If so, make a subclass. Only the instances of the subclass can use the new methods.

Another diff :

In extension, there is no any specific name of extension in swift, but while subclassing there is another name of subclass.

In extension, we can not add variables (fields), in subclass it is possible to declare variables.


How To Access AppDelegate Methods In Other Class?

Ans : 

let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate
appDelegate?.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)

You can make your custom method any called from viewcontroller like :

let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.anyAppDelegateInstaceMethod()

But above is only possible in iOS 10.0 or newer version.

Difference Between If Let And Guard Let?

Ans : 

Basic Difference :

Guard let 

Early exist process from the scope
Require score existing like return, Throw etc.
Create a new variable those can be access out the scope.

if let 

Can not access out the scope.
no need to return statement. But we can write

Note : Both are used to unwrapped the Optional variable.


Guard let


  • A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met. 
  • The value of any condition in a guard statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration.


guard condition else { //Generally return }
func submit() {
guard let name = nameField.text else {
    show("No name to submit")
    return

}

If let
  • Also popular as optional binding 
  • For accessing optional object we use if let
if let roomCount = optionalValue {
        print("roomCount available")
} else {
       print("roomCount is nil")

}



Q. return is mandatory in guard let statement ?
A. Exit is mandatory in guard let statement. So return or throw is mandatory in guard let. Otherwise it gives compile time error.


Difference Between UIWindow And UIView?

Ans :

Windows do not have any visible content themselves but provide a basic container for your application’s views. 

Views define a portion of a window that you want to fill with some content. 

Note : Typically, there is only one window in an iOS application.



What Is IBInspectable And IBDesignable?

Ans : 

IBDesignable and IBInspectable , a way to create custom elements and the attributes . This can be directly added to the iOS Interface Builder.


IBDesignable : 

IBDesignable attribute will identify the UIView or the elements inherited from UIView
i.e: UIButton, UIImageView, UILabel etc

Code :

@IBDesignable
open class KGHighLightedButton: UIButton {

}

IBInspectable : 

@IBInspectable var borderWidth: Double {
        get {
                 return Double(self.layer.borderWidth)
              }
       set {
                 self.layer.borderWidth = CGFloat(newValue)
            }
  }

@IBInspectable var borderColor: UIColor?  {
       get {
                return UIColor(cgColor: self.layer.borderColor!)
             }
      set {
               self.layer.borderColor = newValue?.cgColor
           }
  }

Due to above code, you can set above properties in attribute inspector like following :


So using @IBDesignable and @IBInspectable, you can change make inspectable property and see live changes in IB interface builder without run.

Note : 

IBInspectable can be used with the below types,

Int
CGFloat
Double
String
Bool
CGPoint
CGSize
CGRect
UIColor
UIImage





Wrapping and UnWrapping in Swift

Ans : 

An Optional is basically means that the variable can be nil

i.e: 

var itCanBeNil: String? = “You can make me nil”
itCanBeNil = nil
Question Mark(?) indicates the fact that itCanBeNil Variable can be nil

Let’s try  to make nil a variable which declared without Optional ?

i.e

var itCantBeNil: String = “You can’t make me nil”
itCantBeNil = nil  //Compiler Throws Exception as “Nil cannot be assigned to type ‘String’ ‘”

If we need to get the value from the Variable if it is Optional, we need to unwrap it,
unwrapping is nothing but just putting an exclamation mark at the end

i.e

var itCanBeNil: String? = “Unwrap me”
print(itCanBeNil) //Output: Optional(Unwrap me)
print(itCanBeNil!) //Output: Unwrap me

We can also declare optionals to automatically unwrap by using exclamation mark instead of a question mark

i.e

var itCanBeNil: String! = “Automatic unwrap”

print(itCanBeNil) //No Wrapping needed

What method is called after tap back button in ios?

Ans : 

When you go back the following methods will be called:

Notifies the view controller that its view is about to be added to a view hierarchy : 

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}


Notifies the view controller that its view was added to a view hierarchy : 

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

}

What is stored property and computed property?

Ans : 

1. Stored Property : 

A stored property is a constant or variable that is stored as part of an instance of a particular class or structure. Stored properties can be either variable stored properties (introduced by the var keyword) or constant stored properties (introduced by the let keyword).

struct FixedLengthRange {
    var firstValue: Int
    let length: Int
}

So here, firstValue is mutable (var) storedProperty that can have value and change value,
length is immutable (let) computedProperty that can have value but can not be changed.

We can add property observers to any stored properties you define, except for lazy stored properties.

You have the option to define either or both of these observers on a property:
willSet is called just before the value is stored. (newTotalSteps)
didSet is called immediately after the new value is stored. (oldValue)

2. Computed Property :

Classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

struct Point {
    var x = 0.0, y = 0.0
}
struct Size {
    var width = 0.0, height = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
    var center: Point {
        get {
            let centerX = origin.x + (size.width / 2)
            let centerY = origin.y + (size.height / 2)
            return Point(x: centerX, y: centerY)
        }
        set(newCenter) {
            origin.x = newCenter.x - (size.width / 2)
            origin.y = newCenter.y - (size.height / 2)
        }
    }
}