Search Your Question

Write a program for get only numeric from "a,b,1,2,c,4,d,3"

Ans :  

let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
    if let number = Int(item) {
        print("number: \(number)")
    }

}

Output : 

3
7
10


Write a program to swap between two numbers without third variable

Ans : 

For Int : 

var x = 5
var y = 7

x = x + y
y = x - y
x = x - y

print(x)
print(y)


For Other Types :

var a = "a"
var b = "b"
(b, a) = (a, b)



What is better, Force unwrapping or optional binding?

Ans :

Force unwrapping :  It's the action of extracting the value contained inside an Optional. This operation is dangerous because you are telling the compiler: I am sure this Optional value does contain a real value, extract it!

let anOptionalInt: Int? = 1
let anInt: Int = anOptionalInt!

But here if, anOptionalInt has nil value, then fatal error will be generated. Unexpectedly found nil while unwrapping an Optional value.

Optional Binding: Using if let, we can store value in one variable if value is not nil. By this way, fatal error never be generated. This way will be used when we are not sure that variable has value or nil. This method is better because no chances of crashing app.

if let tempStockCode = stockCode {
    let message = text + tempStockCode
    println(message)
}

Implicitly unwrapped optionals : 

let anOptionalInt: Int! = 1
let anInt: Int = anOptionalInt

anOptionalInt is never be optional. But it can has value of nil.

How much memory will be occupied by integer computed property?

Ans :

No memory will be allocated for computed property. Computed property just compute value and return value. It is not stored any where.

Difference between encapsulation and abstraction.

Ans :

Encapsulation hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hiding something too but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.

Encapsulation: Wrapping code and data together into a single unit. Class is an example of encapsulation, because it wraps the method and property. 
Abstraction: Hiding internal details and showing functionality only. Abstraction focus on what the object does instead of how it does. It provides generalized view of classes.
int number = 5;
string aStringNumber = number.ToString(); 
Here, ToString() is abstraction. And how this mechanism number variable converted to string and initialize into aStringNumber is encapsulation.
We can achieve abstraction using protocol in iOS, achieve encapsulation using access control in class or struct.



How to do geo fencing?

Ans :

Geo-Fence : A Geo-fence is a technology that defines a virtual boundary around a real world geographical area. Every time the user enters or exits the boundary of a certain geofence, actions can be triggered in a location enabled device (often a smartphone). Usually the user will receive a notification with certain information based on its location in real time.

Let's implement : 
In order to work with geofences we need to import CoreLocationframework. After that, we define a locationManager in our viewController and we make the viewController a CLLocationManagerDelegate:


 var locationManager : CLLocationManager = CLLocationManager()


Next, we have to define a region with a center (latitude and longitude) and a radius to monitor. As an example, we are going to define a circular region around the beach in Playa Grande, Mar del Plata with a radius of 400 metres:

 func setUpGeofenceForPlayaGrandeBeach() {
  let geofenceRegionCenter = CLLocationCoordinate2DMake(-38.028308, -57.531508);
  let geofenceRegion = CLCircularRegion(center: geofenceRegionCenter, radius:  400, identifier: "PlayaGrande");
  geofenceRegion.notifyOnExit = true;
  geofenceRegion.notifyOnEntry = true;
  self.locationManager.startMonitoring(for: geofenceRegion)
 }


After creating the region, we are going to set the flags notifyOnExit and notifyOnEntry to true . This will make the CLLocationManagerDelegate trigger a notification each time the user enters or exits the geofenceRegionin the following methods:


func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
  print("Welcome to Playa Grande! If the waves are good, you can try surfing!")
//Good place to schedule a local notification
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
print("Bye! Hope you had a great day at the beach!")
//Good place to schedule a local notification
}




We are still missing the part when the user has to give authorization to the app to track it’s location. So in our viewController we add the following lines to the viewDidLoad method:


 override func viewDidLoad() {
  super.viewDidLoad()
  self.locationManager.requestAlwaysAuthorization()
  self.locationManager.delegate = self
 }

When the user gives authorization to the app, a delegate method is triggered and if the user has given  authorization, we should set up the geofence and start monitoring the region.


 func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  if (status == CLAuthorizationStatus.authorizedAlways) {
    self.setUpGeofenceForPlayaGrandeBeach()
  }
 }

As a last step, we need to add a key to the info.plist with the string to be displayed when asking for location authorization:
<key>NSLocationUsageDescription</key>
<string></string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
Usage of geo-fence in Marketing, Reminders, Child Tracking, Vehicle Tracking, Security, Certain area entry and exit.

What will happened if I delete pod.lock file?

Ans : After first time run pod install, Podfile.lock will be generated.

The purpose of Podfile.lock is tracking of every version of every library that Cocoapods has installed for you, especially working together with a team.

In team there are two guys working, Narendra and Amit.

  • Narendra has made project and install library named Demo Library Version 1.3.3
  • After some days, Demo Library is updated to 1.4.0. and Narendra not hit command pod update  as he is happy with 1.3.3
  • Amit copy narendra's project and hit command pod install, then 1.4.0 will be installed(if Podfile.lock is not there).
  • So here is how Podfile.lock work, record the version of what Narendra had installed, then cocoapods will check what version Narendra had installed and then install on Amit's project. (1.3.0)
  • But if Amit hit command pod update, then in pod.lock file, version changed to 1.4.0 .
So Podfile.lock file should not be deleted if we work on team. And so Podfile.lock file should be checked while using source control.


Everyone should take care while hitting command pod install and pod update. Choose wisely between those. While update pod update, we should ask to our teammate.

Another nice feature is cocoapods will create a snapshot of every library while using source control.

Understand from : Video

When we use pod deinit?

Ans. :

To remove pods from a project completely you need to install two thing first...those are follows(Assuming you have already cocoa-pods installed in your system.)...
  1. Cocoapods-Deintegrate Plugin
  2. Cocoapods-Clean Plugin
Installation
  1. Cocoapods-Deintegrate Plugin
    Use this following command on your terminal to install it.
    sudo gem install cocoapods-deintegrate
  2. Cocoapods-Clean Plugin
    Use this following command on your terminal to install it.
    sudo gem install cocoapods-clean
Usage
First of all goto your project folder by using the as usual command like..
cd (path of the project) //Remove the braces after cd
Now use those two plugins to remove it completely as follows..
  1. Cocoapods-Deintegrate Plugin
    Use this following command on your terminal to deintegrate the pods from your project first.
     pod deintegrate
Deintegrating Pods
  1. Cocoapods-Clean Plugin
    After deintegration of pod from your project use this following command on your terminal to clean it completely.
     pod clean
    After completing the above tasks there should be the Podfile still remaining on your project directory..Just delete that manually or use this following command on the terminal..
     rm Podfile
Thats it...Now you have your project free from pods...Cleaned.
Removing Cocoapods from the system.
Any way try to use the following command on your terminal to uninstall/remove the coca-pods from your system.
sudo gem uninstall cocoapods
It will remove the coca-pods automatically.
Thanks. Hope this helped.

In Objective C, how can avoid crashing of app?

Ans. :

There are multiple aspects to your questions, let me try to answer them:

  • NSSetUncaughtExceptionHandler only catches uncaught exceptions which is only a small subset of possible crashes. 
  • Exceptions in Objective-C are defined to be fatal and it is not recommended to catch them and even more not recommended to run any non-async safe code, which includes any Objective-C and Swift code. 
  • To catch crashes you need to setup signal handlers and then only run async-safe code at the time of the crash, which is only a small subset of C. Especially you may not allocate new memory at crash time at all.

NSSetUncaughtExceptionHandler(&HandleException);
signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);



This will works for most situations.

Difference between objective c and swift protocol

Ans:

Protocol in Objective-C has optional methods and Protocol in Swift has all required methods to implement.

In Swift, Protocol extension is introduced and due to it swift is called protocol oriented language.

Read Protocol Extension to know difference between objective-c and swift protocol

What is NSNotification?

Ans :  Apple has provided an Observer Pattern in the Cocoa library called the NSNotificationCenter.

The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don't have to know about one-another, they just have to know about the broadcaster.

NSNotification is like notifying the other class about the changes that will happen if some action takes place in another class.

Simple :

NSNotificationCenter can be thought of as a broadcaster and we can tune into different stations, or channels to listen for any changes.

Example : 

NotificationCenter.default is where all notifications are posted to and are observed from. Each notification must have a unique way to identify themselves. If we were to observe, or listen, to any channel, we would call on the observe method available to us through NotificationCenter.default and perform some type of action based on this listening.

We have two view controllers named VC1 and VC2. We having observer in VC1 and when we select something in VC2, VC2 post notifications to observer methods.

VC1 :

 func setToIndia(notification: NSNotification) {
     cityChosenLabel.text = "India"
 }
 func setToPakistan(notfication: NSNotification) {
     cityChosenLabel.text = "Pakistan"

 }

Now, we create notification.name extension to set unique name to notification.

 extension Notification.Name {
     static let india = Notification.Name("India")
     static let  pakistan = Notification.Name("Pakistan")
 }

Now we add observer methods,


 NotificationCenter.default.addObserver(self, selector:   #selector(setToIndia(notification:)), name: .india, object: nil)

 NotificationCenter.default.addObserver(self, selector:  #selector(setToPakistan(notfication:)), name: .pakistan, object: nil)


VC2:

We will post notification on selecting something here :


 @IBAction func indiaButton(_ sender: Any) {
     NotificationCenter.default.post(name: .india, object: nil)
 }

 @IBAction func pakistanButton(_ sender: Any) {
      NotificationCenter.default.post(name: .pakistan, object: nil
 }


* When indaButton clicked, Notification Center broadcast notification with message to all listeners name India. 

If you didn't understand still, consider notification center is radio station and our mobile device has observer methods so it can listen radio station's voice.

Simple.....Huah.....






Different types of Control statements.

Ans. 

Control flow statements are used to control the flow of execution in a program.

1. Loop Statement : 

For-in

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")

}


While 
var i:Int = 0
while i < 10 {
    print(i)
    i += 1
}

repeat-while
var j: Int = 10
repeat {
   print(j)
}
while(j < 10)

2. Branch Statement : 

If-else
var numArray = [10, 20, 30, 40, 50, 60, 70]
if(numArray.contains(20)){
    print("true it contains 20")
}else{
    print("number is not there")
}

guard
guard condition else {
    statements
}

The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:  
  • return 
  • break 
  • continue
  •  throw
Switch
switch grade {
    
case 90 ..< 100:
    print("A")
case (80 ..< 90):
    print("B")
case (70 ..< 80):
    print("C")
case (0 ..< 70):
    print("D")
    
default:
    print("F. You failed")//Any number less than 0 or greater than 99
    
}

3. Control Transfer Statement : 
continue 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if(num > 10){
        continue
    }
    print(num)
}

// prints: 10

break 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if num > 30{
        break
    }
    print(num)
}


fallthrough : switch statements don’t fallthrough the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed.

for num in numbersArray{
    switch num {
    case 10:
        print(num)
    case 20:
        print(num)
    case 30:
        print(num)
        fallthrough
    case 40:
        print(num)
    default:
        print("nothing here")
    }
}

return :
func myFunc() -> Int {
    let myNumber = 16 % 3
    if myNumber == 0 {
        return 0
    }
    else if myNumber == 1 {
        return 1
    }
    return 0
}

throw
enum ErrorsToThrow: Error {
    case fileNotFound
    case fileNotReadable
    case fileSizeIsTooHigh
}
class documents {
    
    init() {
        do {
            let dataFromString = try? readFiles(path: "")
            print(dataFromString)
        } catch ErrorsToThrow.fileNotFound {
            print("error generated1")
        } catch ErrorsToThrow.fileNotReadable {
            print("error generated2")
        } catch ErrorsToThrow.fileSizeIsTooHigh {
            print("error generated3")
        } catch {
                print("error")
        }
    }
    
func readFiles(path:String) throws  ->String {
        if path == "" {
            throw ErrorsToThrow.fileNotFound
        }
        return "Data from file"

    }
}