Monday, 15 March 2021

Android Interview Question

Q1: Mention the difference between RelativeLayout and LinearLayout? 

Ans:- 

Linear Layout — Arranges elements either vertically or horizontally. i.e. in a row or column.

Relative Layout — Arranges elements relative to parent or other elements.


Q2: What is the difference between Bitmap and Drawable in Android?  

Answer

A Bitmap is a representation of a bitmap image (something like java.awt.Image).

A Drawable is an abstraction of "something that can be drawn". It could be a Bitmap (wrapped up as a BitmapDrawable), but it could also be a solid color, a collection of other Drawable objects, or any number of other structures.


Q3: What is a difference between Spannable and String?  

Answer

A Spannable allows to attach formatting information like bold, italic, ... to sub-sequences ("spans", thus the name) of the characters. It can be used whenever you want to represent rich text.


Q4: What is an Activity?

Answer

An Activity provides the window in which the app draws its UI.

This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app. For instance, one of an app’s activities may implement a Preferences screen, while another activity implements a Select Photo screen.


Q5: Explain briefly all the Android application components  

Answer

App components are the essential building blocks of an Android app. Each component is an entry point through which the system or a user can enter your app.

There are four different types of app components:

Activities - An activity is the entry point for interacting with the user. It represents a single screen with a user interface.

Services - A service is a general-purpose entry point for keeping an app running in the background for all kinds of reasons. It is a component that runs in the background to perform long-running operations or to perform work for remote processes.

Broadcast receivers - A broadcast receiver is a component that enables the system to deliver events to the app outside of a regular user flow, allowing the app to respond to system-wide broadcast announcements.

Content providers - A content provider manages a shared set of app data that you can store in the file system, in a SQLite database, on the web, or on any other persistent storage location that your app can access.


Q6: What is ADB and what is it used for?

Answer

ADB is the acronym for Android Debug Bridge, which is part of the Android SDK (Software Development Kit). It uses a client-server-model (i.e. adbd, the ADB daemon, is running on the device and can be connected to), and in most cases is used via an USB connection. It is also possible to use it via WiFi (wireless adb).

There's nothing you need to install on your Android device, as the ADB daemon (adbd) is already integrated into the Android OS. It is usually accessed via a command line interface from the PC, where either the full Android SDK is installed (several 30 MB download archive currently), or a massively stripped-down version for "non-developers", sometimes referred to as "Mini ADB" or "ADB essentials" (for Linux, this is only the adb executable; for Windows it's adb.exe plus two or three .dll files).


Q7: In what situation should one use RecyclerView over ListView?

Answer

RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

Reuses cells while scrolling up/down - this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

To conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.


Q8: What is an AsyncTask?  

AsyncTask is one of the easiest ways to implement parallelism in Android without having to deal with more complex methods like Threads. Though it offers a basic level of parallelism with the UI thread, it should not be used for longer operations (of, say, not more than 2 seconds).

AsyncTask has four methods

onPreExecute()

doInBackground()

onProgressUpdate()

onPostExecute()

where doInBackground() is the most important as it is where background computations are performed.


Q10: How do I pass data between Activities in Android application?  

Problem

I have a scenario where, after logging in through a login page, there will be a sign-out button on each activity. Can you guide me on how to keep session id available to all activities?

Answer

The easiest way to do this would be to pass the session id to the signout activity in the Intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);

intent.putExtra("EXTRA_SESSION_ID", sessionId);

startActivity(intent);

Access that intent on next activity:

String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");


Q11: How to persist data in an Android app? 

Answer

There are basically four different ways to store data in an Android app:

Shared Preferences - to save primitive data in key-value pairs

Internal Storage - you need to store data to the device filesystem, but you do not want any other app (even the user) to read this data

External Storage - you might want the user to view the files and data saved by your app

SQLite database


Q12: Why is it recommended to use only the default constructor to create a Fragment? 

Answer

In short, Fragments need to have a no-args constructor for the Android system to instantiate them. Your Fragment subclasses need a public empty constructor as this is what's being called by the framework.

It is used in the case when device has to restore the state of a fragment. No data will be passed and a default fragment will be created and then the state will be restored. Since the system has no way to know what you passed in your constructor or your newInstance, default constructor will be used and saved bundle should be passed via onCreate after the fragment is actually instantiated with the default constructor.


Q13: What is View Group? How are they different from Views?

Answer

View: View objects are the basic building blocks of User Interface(UI) elements in Android. View is a simple rectangle box which responds to the user’s actions. Examples are EditText, Button, CheckBox etc. View refers to the android.view.View class, which is the base class of all UI classes.

ViewGroup: ViewGroup is the invisible container. It holds View and ViewGroup. For example, LinearLayout is the ViewGroup that contains Button (View), and other Layouts also. ViewGroup is the base class for Layouts.


Q14: What is Dalvik?  

Dalvik is a Just In Time (JIT) compiler.

By the term JIT, we mean to say that whenever you run your app in your mobile device then that part of your code that is needed for execution of your app will only be compiled at that moment and rest of the code will be compiled in the future when needed. The JIT or Just In Time compiles only a part of your code and it has a smaller memory footprint and due to this, it uses very less physical space on your device.


Q15: What’s the difference between onCreate() and onStart()? 

Answer

The onCreate() method is called once during the Activity lifecycle, either when the application starts, or when the Activity has been destroyed and then recreated, for example during a configuration change.

The onStart() method is called whenever the Activity becomes visible to the user, typically after onCreate() or onRestart().


Q16: Explain activity lifecycle  

As a user navigates through, out of, and back to your app, the Activity instances in your app transition through different states in their lifecycle.

To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). The system invokes each of these callbacks as an activity enters a new state.


Q17: What is the most appropriate way to store user settings in Android application?

Answer

In general SharedPreferences are your best bet for storing preferences, so in general I'd recommend that approach for saving application and user settings.

The only area of concern here is what you're saving. Passwords are always a tricky thing to store, and I'd be particularly wary of storing them as clear text. The Android architecture is such that your application's SharedPreferences are sandboxed to prevent other applications from being able to access the values so there's some security there, but physical access to a phone could potentially allow access to the values.


Q18: Explain Android notification system  

Answer

A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.

Notifications appear to users in different locations and formats, such as an icon in the status bar, a more detailed entry in the notification drawer, as a badge on the app's icon, and on paired wearables automatically. Beginning with Android 5.0, notifications can appear on the lock screen.

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. By categorizing notifications into channels, users can disable specific notification channels for your app (instead of disabling all your notifications), and users can control the visual and auditory options for each channel—all from the Android system settings.


Q19: What is an Intent in Android? 

Answer

An Intent is basically a message that is passed between components (such as Activities, Services, Broadcast Receivers, and Content Providers).So, it is almost equivalent to parameters passed to API calls. The fundamental differences between API calls and invoking components via intents are:

API calls are synchronous while intent-based invocations are asynchronous.

API calls are compile-time binding while intent-based calls are run-time binding.

To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another's app intent like "take picture", you declare an intent filter in your app's manifest file.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.

An Intent provides a facility for performing late runtime binding between the code in different applications.


Q20: What is a ContentProvider and what is it typically used for?

Answer

A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object.

Typically you work with content providers in one of two scenarios;

you may want to implement code to access an existing content provider in another application, or

you may want to create a new content provider in your application to share data with other applications.


Q21: Is it possible to implement the Model–View–Controller pattern in Java for Android?

Answer

In Android you don't have MVC, but you have the following:

You define your user interface in various XML files by resolution, hardware, etc.

You define your resources in various XML files by locale, etc.

You extend clases like ListActivity, TabActivity and make use of the XML file by inflaters.

You can create as many classes as you wish for your business logic.

A lot of Utils have been already written for you - DatabaseUtils, Html.


Q22: How does the OutOfMemory happens?

Answer

Out of memory error is very common error when you are developing for a application that deals with multiple images sets or large bitmaps or some Animation stuff. In Android, every application runs in a Linux Process. Each Linux Process has a Virtual Machine (Dalvik Virtual Machine) running inside it. There is a limit on the memory a process can demand and it is different for different devices and also differs for phones and tablets. When some process demands a higher memory than its limit it causes a error i.e Out of memory error.

There are number of reasons why we get a Out of memory errors. Some of those are:

1. You are doing some operation that continuously demands a lot of memory and at some point it goes beyond the max heap memory limit of a process.

2. You are leaking some memory i.e you didn’t make the previous objects you allocated eligible for Garbage Collection (GC). This is called Memory leak.

3. You are dealing with large bitmaps and loading all of them at run time. You have to deal very carefully with large bitmaps by loading the size that you need not the whole bitmap at once and then do scaling.


Q23: What is Armv7? 

Answer

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It's similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it's more flexible than RelativeLayout and easier to use with Android Studio's Layout Editor.

Intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.


Q25: How can I get the context in a Fragment?

You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context). You can also override the onAttach() method of fragment:

public static class DummySectionFragment extends Fragment{

...

    @Override

    public void onAttach(Activity activity) {

        super.onAttach(activity);

        DBHelper = new DatabaseHelper(activity);

    }

}


Q26: What types of Context do you know?

Answer

The are mainly two types of context:

1. Application Context: It is an instance that is the singleton and can be accessed in activity via getApplicationContext(). This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of activity.

2. Activity Context: This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.


Q28: What is Context on Android? 

Answer

The documentation itself provides a rather straightforward explanation: The Context class is an Interface to global information about an application environment.

We may assume a Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.


Q29: What is the difference between compileSdkVersion and targetSdkVersion?

Answer

compileSdkVersion

The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.


targetSdkVersion

The targetSdkVersion has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.


What are Android Annotations and what are they used for?

Answer

Android Annotations is an annotation-driven framework that allows you to simplify the code in your applications and reduces the boilerplate of common patterns, such as setting click listeners, enforcing ui/background thread executions, etc.


What is Parcelable in Android?

A Parcelable is the Android implementation of the Java Serializable. ... To allow your custom object to be parsed to another component they need to implement the android. os. Parcelable interface. It must also provide a static final method called CREATOR which must implement the Parcelable.


When to use Android's ArrayMap instead of a HashMap?

Answer

HashMap uses an array underneath so it can never be faster than using an array correctly.


Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.The reason your array is so slow is due to the equals comparisons, not the array access itself.


An ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.


List:


An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.


Map:


An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.


The list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background. You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).


The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarantee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).


When to use Arrays?


Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.


Sometimes, it may be best to use a combination of the above approaches. For example, you could use a ArrayList of HashMap to suit a particular need.


What is Intent Filter?

An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml. Android must know what kind of intent it is launching so intent filters give the information to android about intent and actions.


What is an implicit intent?

Answer

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you'd like the user to pick which app to use


What is Explicit Intent? 

Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent.


We can also pass the information from one activity to another using explicit intent.


What does LayoutInflater in Android do?

Answer

The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects. In other words, it takes an XML file as input and builds the View objects from it.


Explain String vs StringBuilder vs SpannedString vs SpannableString vs SpannableStringBuilder vs CharSequence? 

Answer

String

A String is immutable (ie, the text can't change). It also doesn't have any spans associated with it. (Spans are ranges over the text that include styling information like color, highlighting, italics, links, etc.) So you can use a String when your text doesn't need to be changed and doesn't need any styling.


StringBuilder

A StringBuilder has mutable text, so you can modify it without creating a new object. However, it doesn't have any span information. It is just plain text. So use a StringBuilder when you need to change the text, but you don't care about styling it.


SpannedString

A SpannedString has immutable text (like a String) and immutable span information. It is a concrete implementation of the requirements defined by the Spanned interface. Use a SpannedString when your text has style but you don't need to change either the text or the style after it is created.


Note: There is no such thing as a SpannedStringBuilder because if the text changed then the span information would also very likely have to change.


SpannableString

A SpannableString has immutable text, but its span information is mutable. It is a concrete implementation of the requirements defined by the Spannable interface. Use a SpannableString when your text doesn't need to be changed but the styling does.


SpannableStringBuilder

A SpannableStringBuilder has both mutable text and span information. It is a concrete implementation of the requirements defined by the Spannable and Editable interfaces (among others). Use a SpannableStringBuilder when you will need to update the text and its style.


CharSequence

A CharSequence is an interface and not a concrete class. That means it just defines a list of rules to follow for any class that implements it. And all of the classes mentioned above implement it. So you can use a CharSequence when you want to generalize the type of object that you have for maximum flexibility. You can always downcast it to a String or SpannableStringBuilder or whatever later if you need to.


What is the difference between Handler vs AsyncTask vs Thread? 

Answer

Thread


Android supports standard Java Threads. You can use standard Threads and the tools from the package “java.util.concurrent” to put actions into the background. The only limitation is that you cannot directly update the UI from the a background process.


If you need to update the UI from a background task you need to use some Android specific classes. You can use the class “android.os.Handler” for this or the class “AsyncTask”


Handler


The class “Handler” can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and override handleMessage() to process messages. To process Runable, you can use the method post(); You only need one instance of a handler in your activity.


You thread can post messages via the method sendMessage(Message msg) or sendEmptyMessage.


AsyncTask


If you have an Activity which needs to download content or perform operations that can be done in the background AsyncTask allows you to maintain a responsive user interface and publish progress for those operations to the user.



How would you communicate between two Fragments?

Answer

The recommended way to communicate between fragments is to create a shared ViewModel . Both fragments can access the ViewModel through their containing Activity.


 What is the difference between Service & Intent Service? 

 Answer

 Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.


IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work


What are the differences between ArrayList and ArrayMap?

Answer

ArrayMap keeps its mappings in an array data structure — an integer array of hash codes for each item, and an Object array of the key -> value pairs.


Where ArrayList is a List. Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.


What is the difference between Activity and Context? 

Answer


What is a JobScheduler?

Answer

This is an API for scheduling various types of jobs against the framework that will be executed in your application's own process. See JobInfo for more description of the types of jobs that can be run and how to construct them.



What is the difference between onCreate() and onCreateView() lifecycle methods in Fragment?

Answer

onCreate() : Initialize essential components and variables of the Fragment in this callback. The system calls this method when the Fragment is created. Anything initialized in onCreate() is preserved if the Fragment is paused and resumed. onCreateView() : Inflate the XML layout for the Fragment in this callback.


What is the difference between a Bundle and an Intent?

Answer



what is singleton class in android

Answer

A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency and creating a central point of access for an application to access its data store. This example demonstrate about How to use singleton class in android.


what is application context in android

Answer

 It is the context of the current state of the application. It can be used to get information regarding the activity and application. It can be used to get access to resources, databases, and shared preferences, and etc. Both the Activity and Application classes extend the Context class


 What are some difference between Parcelable and Serializable? 

 Answer

 Serializable


Serializable is a markable interface or we can call as an empty interface. It doesn’t have any pre-implemented methods. Serializable is going to convert an object to byte stream. So the user can pass the data between one activity to another activity. The main advantage of serializable is the creation and passing data is very easy but it is a slow process compare to parcelable.


Parcelable


Parcelable is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn’t create more temp objects while passing the data between two activities.


Difference between SparseArray and Hashmap?

Answer



What is Broadcast Receiver?

Answer

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.


What are ‘activities’? Describe the lifecycle of an activity.

Answer

OnCreate(): Here, the views are created and data is collected from bundles.

OnStart(): It is called if the activity is visible to the user. It may be succeeded by onResume() if the activity reaches the foreground and onStop() if it converts into hidden.

OnResume(): It is called when the activity starts an interaction with the user.

OnPause(): This is called when the activity is going to the background but hasn’t been killed yet.

OnStop(): This is called when you are no longer visible to the user.

OnDestroy(): Called when the activity is finishing

OnRestart(): Called after the activity has been stopped, prior to it being started again


Question: How do you find memory leaks in an application on the Android platform?

Answer: To find memory leaks in an application on Android, the Android Device Manager (ADM) is used by the Android Studio. When you open ADM in Android Studio, you can see parameters such as heap size and memory analysis along with many others while you run an application.


Question: State the architecture of an Android application.

Answer: Any Android application has the following components:


Notification- Features such as light, sound, icons and more

Services- To perform background functionalities

Intent- To perform inter-connection between activities and mechanisms that pass on data

Resource Externalization- Features such as strings and graphics

Content Providers- To share data between applications


Question: Explain the difference between implicit and explicit intent.

Answer: Below is the difference between the two intents


Explicit Intent: An explicit intent is where you inform the system about which activity or system component it should use to generate a response to this intent.

Implicit Intent: An implicit intent allows you to declare the action you wish to carry out, after which the Android system will check which components are registered to handle that specific action.


Question: Explain different launch modes in Android

Answer: Below are the different launch modes in Android


Standard: This launch mode generates a new instance of the activity in the task from which it originated. It is possible to create multiple instances of the same activity, which can be added to the same or different tasks.

SingleTop: This launch mode is similar to the Standard launch mode, except if there exists a previous instance of the activity on the top of the stack, then a new instance will not be created, but the intent will be sent to the existing instance of the activity.

SingleTask: This launch mode will always create a new task and push a new instance to the task as the root one.

SingleInstance: This launch mode is the same as the SingleTask launch mode but the system doesn’t launch any new activities in the same task. In a scenario where the new activity is launched, it is launched in a separate task.

Thursday, 11 March 2021

IOS Interview Question

 1.What is the difference between a UIAlertView and a UIAlertController?

Ans: The UIAlertView class has a simple interface and is used to present modal alerts. Apple has deprecated UIAlertView in iOS 8 though. As of iOS 8, it is recommended to use the UIAlertController class to present action sheets and modal alerts.

2. Can you explain MVC, and how it's used on Apple's platforms?

Ans: MVC – short for Model-View-Controller – is Apple's preferred way of architecting apps for its platforms, and so it's the default approach used by most developers on Apple platforms. In MVC each piece of your code is one of three things: Models store your data, such as the names of products in a store

3. What is the difference between an extension and a protocol extension?

Ans: Protocols let you describe what methods something should have, but don't provide the code inside. Extensions let you provide the code inside your methods, but only affect one data type – you can't add the method to lots of types at the same time.

4. What problem does optional chaining solve?

Ans: The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null . For example, consider an object obj which has a nested structure.

5. What is the purpose of NotificationCenter?

Ans: It helps for observation and broadcasting singles from one class to multiple classes. Post singles from one class to multiple classes. Receiving singles from multiple classes.

6. What is the purpose of IBDesignable?

Ans:. When applied to a UIView or NSView subclass, the @IBDesignable designation lets Interface Builder know that it should render the view directly in the canvas. This allows seeing how your custom views will appear without building and running your app after each change

7. What is an efficient way to cache data in memory?

Ans:. There are lots of ways of making caches, but NSCache is definitely preferable because it gets cleared by the system when memory is low.

8. What are property observers?

Ans:-Property Observers. Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.

9. How much experience do you have using Core Image? Can you give examples?

Ans:- Some developers confuse Core Graphics and Core Image, which is a mistake – they are quite different. Core Image is less used, but is helpful for filtering images: blurring or sharpening, adjusting colors, and so on

10. What are the main differences between classes and structs in Swift?

Ans:  In Swift, structs are value types whereas classes are reference types. When you copy a struct, you end up with two unique copies of the data. When you copy a class, you end up with two references to one instance of the data. It's a crucial difference, and it affects your choice between classes or structs.

11. What is a variadic function?

Ans:- Variadic functions accept any number of parameters. Swift writes them using ..., and we’re handed the parameters as an array. Again, try to give an example – something like print() is a good place to start.

12. what is p12 certificate

Ans:.p12 is an alternate extension for what is generally referred to as a "PFX file", it's the combined format that holds the private key and certificate and is the format most modern signing utilities use. If you have a . p12 file that you exported from Firefox or Safari just rename the . p12 extension to

13. what is typealias in swift

Ans:- Swift Typealias is used to provide a new name for an existing data type in the program. Once you create a typealias, you can use the aliased name instead of the exsisting name throughout the program. Typealias doesn't create a new data type, it simply provides a new name to the existing data type.

14. What is the purpose of UIMenuController?

Ans: UIMenuController class is used to display an editing menu over the UI element. The editing menu is a rectangular box with different actions. By default, there are some inbuilt actions such as cut, copy, paste, lookup, replace, define etc.

15. What is UserDefaults good for? What is UserDefaults not good for?

Ans:- This should immediately have you thinking about speed, size, and security: UserDefaults is bad at large amounts of data because it slows your app load, it’s annoying for complex data types because of NSCoding, and a bad choice for information such as credit cards and passwords – recommend the keychain instead.

16. What is PLIST in iOS?

Ans:- PLIST stands for Property List. PLIST is basically a dictionary of value and keys that can be stored in our file system with a .plist file extension. The property list is used as a portable and lightweight means to store a lesser amount of data. They are normally written in XML.

17. What is a dictionary?

Ans: Dictionaries are an association of an unordered collection of key-value pairs. Each value is associated with a unique key, which is a hashable type such as a number or string. We can use the dictionary concept in swift programming language whenever we want to obtain the values based on a key value.

18. What is a Protocol in swift?

Ans: The protocol is a very common feature of the Swift programming language and the protocol is a concept that is similar to an interface from java. A protocol defines a blueprint of properties, methods, and other requirements that are suitable for a particular task.

In its simplest form, the protocol is an interface that describes some methods and properties. The protocol is just described as the properties or methods skeleton instead of implementation. Properties and methods implementation can be done by defining enumerations, functions, and classes.

Protocols are declared after the structure, enumeration or class type names. A single and multiple protocol declaration can be possible. Multiple protocols are separated by commas.

19. What is the use of double question mark “??” in swift?

Ans:- The double question mark “??” is a nil-coalescing operator, it is mainly a shorthand for the ternary conditional operator where we used to test for nil. A double question mark is also used to provide a default value for a variable.  stringVar ?? “default string”  This exactly does the common thing, if stringVar is not nil then it is returned, otherwise the “default string” is returned.

20. What is a GUARD statement? What is the benefit of using the GUARD statement in swift?

Ans:- A GUARD statement is used to transfer the program control out of the scope when one or more conditions are not met. Using this statement helps in avoiding the pyramid of doom.

21. What is the difference between Array and NSArray?

Ans: The difference between Array and NSArray are given below:  

An array can hold only one type of data, whereas NSArray can hold different types of data. 

An array is a value type, whereas NSArray is an immutable reference type.       

22. What is the difference between class and structure?

Ans: The difference between class and structure are given below:  

Classes are reference types, whereas structs are value types. 

Classes can be built on other classes, whereas struct cannot inherit from another struct. 

Classes have an inheritance, whereas structs cannot have an inheritance. 

In class, we can create an instance with “let” keywords and attempt to mutate its property, whereas there is no Mutability in Structs. 

Classes have Type Casting, whereas struct doesn’t have Type Casting.

23. How to pass the data between view controllers?

Ans: There are three ways to pass the data between view controllers as shown below.  

Using Segue, in prepareForSegue method (Forward). 

Setting the variable directly (Backword). 

Using Delegate (Backword).

24. What are the different ways to pass data in swift?

Ans: - There are several ways to pass data in swift such as KVO, Delegate, NSNotification & Callbacks, Target-Action, etc.

25. Explain the usage of Class and benefits of Inheritance.

Ans:- They are:

 Reuse implementation Subclass provides dynamic dispatch. 

Subclass provides the reuse interface.

 Modularity 

Overriding provides the mechanism for customization.

26. Explain some Common features of Protocols & Superclasses.

Ans: Some common features of Protocol & Superclass are given below: 

Interface reuse. 

Implementation reuse. 

Supporting modular design. 

Provides points for customization.

27. Explain some biggest changes in UserNotifications.

Ans: Some bigger changes in UserNotifications are given below: 

Allows adding images, audio, and videos. 

Allows creating custom interfaces for notifications. 

Allows managing the notifications with interface in the notification center.

28. What are the Higher-Order functions in swift?

Ans:- The higher-order functions are given below: 

Map: Transform the array contents. 

Reduce: Reduce the values in the collection to a single value. 

Sort: Sorting the arrays. 

Filter: Transform the array contents.

30. What are the various ways to unwrap an optional in swift?

Ans:-There are seven ways to unwrap an optional in swift. They are: 

Guard statement: safe. 

Forced unwrapping: using “!” operator, unsafe.

 Optional binding: safe. Optional pattern: safe. 

Nil coalescing operator: safe. 

Implicitly unwrapped variable declaration: unsafe in many cases. 

Optional chaining: safe.

31. What mechanism does iOS support for multi-threading?

Ans: They are: 

NSThread: It can create a low-level thread which can be started by using the “start” method. NSOperationQueue: It allows a pool of threads to be created and is used to execute “NSOperations” in parallel.

32. What is Swift module?

Ans: 

  • A module is a single unit of code distribution.
  • A framework or application is built and shipped as a single unit and that can be imported by another module using the swift import keyword.
  • Each build target in the Xcode tool is treated as a separate module in swift.

33.When would you use the guard keyword in Swift?
Ans: A guard statement is used to transfer program control out of a scope if one or more conditions aren't met. A guard statement has the following form: guard condition else { statements.

34. What is the difference between try, try?, and try! in Swift?
Ans: A regular try requires you to catch errors, try? converts the throwing call into an optional where you’ll get back nil on failure, and try! will cause your app to crash if the throwing call fails. All three have their uses!

35. What is the function of anchors in Auto Layout?
Ans: Auto Layout anchors make it easy to position your views relative to others. There are lots of anchors to choose from: leading and trailing edges, top and bottom edges, center X and center Y, and more.

36. When would you use the defer keyword in Swift?
Ans: This is used to delay a piece of work until a method ends. Try to give a specific example, such as saving a file once everything has been written.

37. How does CloudKit differ from Core Data?
Ans: Core Data on its own, is completely local and does not automatically work with any of Apple's cloud services. Core Data with iCloud enabled turns on syncing via iCloud. ... CloudKit does not store data on the device, so the data is not available if the device is offline.

38. What is the difference between aspect fill and aspect fit when displaying an image?
Ans: Aspect fit ensures all parts of the image are visible, whereas aspect fill may crop the image to ensure it takes up all available space.

39. What are tuples and why are they useful?
Ans: Tuples are a bit like anonymous structs, and are helpful for returning multiple values from a method in a type-safe way, among other things.

40. What is the difference between weak and unowned?
Ans. “Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.”

41. What does the #available syntax do?
Ans: This syntax was introduced in Swift 2.0 to allow run-time version checking of features by OS version number. It allows you to target an older version of iOS while selectively limiting features available only in newer iOS versions.

1- How could you set up Live Rendering?
The attribute @IBDesignable lets Interface Builder perform live updates on a particular view. IBDesignable requires Init frame to be defined as well in UIView class.

2- What is the difference between Synchronous & Asynchronous task?
Synchronous: waits until the task have completed Asynchronous: completes a task in the background and can notify you when complete

3- Explain Compilation Conditions
Compilation Conditions to use if DEBUG … endif structure to include or disable given block of code ve separate targets.

4- What is made up of NSError object?
There are three parts of NSError object a domain, an error code, and a user info dictionary. The domain is a string that identifies what categories of errors this error is coming from.

6- What is the bounding box?
The bounding box is a term used in geometry; it refers to the smallest measure (area or volume) within which a given set of points.

7- Why don’t we use strong for enum property in Objective-C?
Because enums aren’t objects, so we don’t specify strong or weak here.

8- What is @synthesize in Objective-C?
synthesize generates getter and setter methods for your property.

9- What is @dynamic in Objective-C?
We use dynamic for subclasses of NSManagedObject. @dynamic tells the compiler that getter and setters are implemented somewhere else.

10- Why do we use synchronized?
synchronized guarantees that only one thread can be executing that code in the block at any given time.

11- What is the difference strong, weaks, read only and copy?

strongweakassign property attributes define how memory for that property will be managed.

Strong means that the reference count will be increased and
the reference to it will be maintained through the life of the object

Weak ( non-strong reference ), means that we are pointing to an object but not increasing its reference count. It’s often used when creating a parent child relationship. The parent has a strong reference to the child but the child only has a weak reference to the parent.

  • Every time used on var
  • Every time used on an optional type
  • Automatically changes itself to nil

Read-only, we can set the property initially but then it can’t be changed.

Copy means that we’re copying the value of the object when it’s created. Also prevents its value from changing.

for more details check this out

12- What is Dynamic Dispatch?
Dynamic Dispatch is the process of selecting which implementation
of a polymorphic operation that’s a method or a function to call at run time. This means, that when we wanna invoke our methods like object method. but Swift does not default to dynamic dispatch

13- What’s Code Coverage?
Code coverage is a metric that helps us to measure the value of our unit tests.

14- What’s Completion Handler?
Completion handlers are super convenient when our app is making an API call, and we need to do something when that task is done, like updating the UI to show the data from the API call. We’ll see completion handlers in Apple’s APIs like dataTaskWithRequest and they can be pretty handy in your own code.

The completion handler takes a chunk of code with 3 arguments:(NSData?, NSURLResponse?, NSError?) that returns nothing: Void. It’s a closure.

15- How to Prioritize Usability in Design ?
Broke down its design process to prioritize usability in 4 steps:

  • Think like the user, then design the UX.
  • Remember that users are people, not demographics.
  • When promoting an app, consider all the situations in which it could be useful.
  • Keep working on the utility of the app even after launch.

16- What’s the difference between the frame and the bounds?
The bounds of a 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 a UIView is the rectangle, expressed as a location (x,y) and size (width, height) relative to the superview it is contained within.

17- What is Responder Chain ?
A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.

18- What is Regular expressions?
Regular expressions are special string patterns that describe how to search through a string.

19- What is Operator Overloading?
Operator overloading allows us to change how existing operators behave with types that both already exist. Operators are those little symbols like +*, and /

20- What is TVMLKit?
TVMLKit is the glue between TVML, JavaScript, and your native tvOS application.

21- What is Platform limitations of tvOS?
First
, tvOS provides no browser support of any kind, nor is there any WebKit or other web-based rendering engine you can program against. This means your app can’t link out to a web browser for anything, including web links, OAuth, or social media sites.

Second, tvOS apps cannot explicitly use local storage. At product launch, the devices ship with either 32 GB or 64 GB of hard drive space, but apps are not permitted to write directly to the onboard storage.

tvOS app bundle cannot exceed 4 GB.

22- What is Functions?
Functions let us group a series of statements together to perform some task. Once a function is created, it can be reused over and over in your code. If you find yourself repeating statements in your code, then a function may be the answer to avoid that repetition.

Pro Tip, Good functions accept input and return output. Bad functions set global variables and rely on other functions to work.

23- What is ABI?
ABIs are important when it comes to applications that use external libraries. If a program is built to use a particular library and that library is later updated, you don’t want to have to re-compile that application (and from the end user's standpoint, you may not have the source). If the updated library uses the same ABI, then your program will not need to change. ABI stability will come with Swift 5.0

            

24- Why is design pattern very important ?
Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. Most common Cocoa design patterns:

  • Creational: Singleton.
  • Structural: Decorator, Adapter, Facade.
  • Behavioral: Observer, and, Memento

25- What is Singleton Pattern ?
The Singleton design pattern ensures that only one instance exists for a given class and that there’s a global access point to that instance. It usually uses lazy loading to create the single instance when it’s needed the first time.

26- What is Facade Design Pattern?
The Facade design pattern provides a single interface to a complex subsystem. Instead of exposing the user to a set of classes and their APIs, you only expose one simple unified API.

27- What is Decorator Design Pattern?
The Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code. It’s an alternative to subclassing where you modify a class’s behavior by wrapping it with another object.

In Objective-C there are two very common implementations of this pattern: Category and Delegation. In Swift there are also two very common implementations of this pattern: Extensions and Delegation.

28- What is Adapter Pattern?
An Adapter allows classes with incompatible interfaces to work together. It wraps itself around an object and exposes a standard interface to interact with that object.

29- What is Observer Pattern?
In the Observer pattern, one object notifies other objects of any state changes.

Cocoa implements the observer pattern in two ways: Notifications and Key-Value Observing (KVO).

30- What is Memento Pattern?
In Memento Pattern saves your stuff somewhere. Later on, this externalized state can be restored without violating encapsulation; that is, private data remains private. One of Apple’s specialized implementations of the Memento pattern is Archiving other hand iOS uses the Memento pattern as part of State Restoration.

31- Explain MVC

  • Models — responsible for the domain data or a data access layer which manipulates the data, think of ‘Person’ or ‘PersonDataProvider’ classes.
  • Views — responsible for the presentation layer (GUI), for iOS environment think of everything starting with ‘UI’ prefix.
  • Controller/Presenter/ViewModel — the glue or the mediator between the Model and the View, in general responsible for altering the Model by reacting to the user’s actions performed on the View and updating the View with changes from the Model.

32- Explain MVVM
UIKit independent representation of your View and its state. The View Model invokes changes in the Model and updates itself with the updated Model, and since we have a binding between the View and the View Model, the first is updated accordingly.

Your view model will actually take in your model, and it can format the information that’s going to be displayed on your view.

There is a more known framework called RxSwift. It contains RxCocoa, which are reactive extensions for Cocoa and CocoaTouch.

33- How many different annotations available in Objective-C ?

  • _Null_unspecified, which bridges to a Swift implicitly unwrapped optional. This is the default.
  • _Nonnull, the value won’t be nil it bridges to a regular reference.
  • _Nullable the value can be nil, it bridges to an optional.
  • _Null_resettable the value can never be nil, when read but you can set it to know to reset it. This is only apply property.

34- What is JSON/PLIST limits ?

  • We create your objects and then serialized them to disk..
  • It’s great and very limited use cases.
  • We can’t obviously use complex queries to filter your results.
  • It’s very slow.
  • Each time we need something, we need to either serialize or deserialize it.
  • it’s not thread-safe.

35- What is SQLite limits ?

  • We need to define the relations between the tables. Define the schema of all the tables.
  • We have to manually write queries to fetch data.
  • We need to query results and then map those to models.
  • Queries are very fast.

36- What is Realm benefits ?

  • An open-source database framework.
  • Implemented from scratch.
  • Zero copy object store.
  • Fast.

37- How many are there APIs for battery-efficient location tracking ?
There are 3 apis.

  • Significant location changes — the location is delivered approximately every 500 metres (usually up to 1 km)
  • Region monitoring — track enter/exit events from circular regions with a radius equal to 100m or more. Region monitoring is the most precise API after GPS.
  • Visit events — monitor place Visit events which are enters/exits from a place (home/office).

38- What is the Swift main advantage ?
To mention some of the main advantages of Swift:

  • Optional Types, which make applications crash-resistant
  • Built-in error handling
  • Closures
  • Much faster compared to other languages
  • Type-safe language
  • Supports pattern matching

39- Explain generics in Swift ?
Generics create code that does not get specific about underlying data types. Don’t catch this article. Generics allow us to know what type it is going to contain. Generics also provides optimization for our code.

40- Explain lazy in Swift ?
An initial value of the lazy stored properties is calculated only when the property is called for the first time. There are situations when the lazy properties come very handy to developers.

41- Explain what is defer ?
defer keyword which provides a block of code that will be executed in the case when execution is leaving the current scope.

42- How to pass a variable as a reference ?
We need to mention that there are two types of variables: reference and value types. The difference between these two types is that by passing value type, the variable will create a copy of its data, and the reference type variable will just point to the original data in the memory.

43- How to pass data between view controllers?

There are 3 ways to pass data between view controllers.

  1. Segue, in prepareForSegue method (Forward)
  2. Delegate (Backward)
  3. Setting variable directly (Forward)

44- What is Concurrency ?
Concurrency is dividing up the execution paths of your program so that they are possibly running at the same time. The common terminology: process, thread, multithreading, and others. Terminology;

  • Process, An instance of an executing app
  • Thread, Path of execution for code
  • Multithreading, Multiple threads or multiple paths of execution running at the same time.
  • Concurrency, Execute multiple tasks at the same time in a scalable manner.
  • Queues, Queues are lightweight data structures that manage objects in the order of First-in, First-out (FIFO).
  • Synchronous vs Asynchronous tasks

45- Grand Central Dispatch (GCD)
GCD
 is a library that provides a low-level and object-based API to run tasks concurrently while managing threads behind the scenes. Terminology;

  • Dispatch Queues, A dispatch queue is responsible for executing a task in the first-in, first-out order.
  • Serial Dispatch Queue A serial dispatch queue runs tasks one at a time.
  • Concurrent Dispatch Queue A concurrent dispatch queue runs as many tasks as it can without waiting for the started tasks to finish.
  • Main Dispatch Queue A globally available serial queue that executes tasks on the application’s main thread.

46- Readers-Writers
Multiple threads reading at the same time while there should be only one thread writing. The solution to the problem is a readers-writers lock which allows concurrent read-only access and an exclusive write access. Terminology;

  • Race Condition A race condition occurs when two or more threads can access shared data and they try to change it at the same time.
  • Deadlock A deadlock occurs when two or sometimes more tasks wait for the other to finish, and neither ever does.
  • Readers-Writers problem Multiple threads reading at the same time while there should be only one thread writing.
  • Readers-writer lock Such a lock allows concurrent read-only access to the shared resource while write operations require exclusive access.
  • Dispatch Barrier Block Dispatch barrier blocks create a serial-style bottleneck when working with concurrent queues.

47- NSOperation — NSOperationQueue — NSBlockOperation
NSOperation
 adds a little extra overhead compared to GCD, but we can add dependency among various operations and re-use, cancel or suspend them.

NSOperationQueue, It allows a pool of threads to be created and used to execute NSOperations in parallel. Operation queues aren’t part of GCD.

NSBlockOperation allows you to create an NSOperation from one or more closures. NSBlockOperations can have multiple blocks, that run concurrently.

48- KVC — KVO
KVC
 adds stands for Key-Value Coding. It’s a mechanism by which an object’s properties can be accessed using string’s at runtime rather than having to statically know the property names at development time.

KVO stands for Key-Value Observing and allows a controller or class to observe changes to a property value. In KVO, an object can ask to be notified of any changes to a specific property, whenever that property changes value, the observer is automatically notified.

49- Please explain Swift’s pattern matching techniques

  • Tuple patterns are used to match values of corresponding tuple types.
  • Type-casting patterns allow you to cast or match types.
  • Wildcard patterns match and ignore any kind and type of value.
  • Optional patterns are used to match optional values.
  • Enumeration case patterns match cases of existing enumeration types.
  • Expression patterns allow you to compare a given value against a given expression.

50- Explain Guard statement
There are three big benefits to guard statement.

One is avoiding the pyramid of doom, as others have mentioned — lots of annoying if let statements nested inside each other moving further and further to the right. The second benefit is providing an early exit out of the function using break or using return.

The last benefit, guard statement is another way to safely unwrap optionals.