Tech Interview

Swift (iOS) Interview Questions

op Swift (iOS) Interview Questions and Answers with Examples:

Swift is a powerful and interactive programming language created for iOS, macOS, tvOS and watchOS, and Linux development by Apple Inc.

Swift is a fantastic way to develop software, it is an interactive programming language that is fast, safe, and friendly to new programs. Swift is the most popular language for developing apps for Apple’s devices, it is an alternative to the Objective-C language with some added object-oriented features.

Swift (iOS) Interview Questions

Here is a list of the top iOS Swift interview tips and questions along with the answers.

 

Q #1) What is iOS Swift?

Answer: Swift is a compiled and new programming language evolved by Apple Inc in June 2014 in order to develop apps for mobile and desktop. This language works for watchOS, macOS, iOS, and tvOS.

Apple created Swift language to work with both Cocoa Touch and Cocoa. Swift supports multiple operating systems such as Free BSD, Linux, Darwin, etc. This language was designed to work along with the Objective-C library and Cocoa framework in the Apple products.

Q #2) What are the advantages of using Swift?

Answer: Swift programming language has speedily become one of the quick-growing languages in memoir. Swift makes us develop software that is incredibly fast, robust and secure.

This language is the most useful programming language that is used to develop an application for macOS and iOS(iPad and iPhone).

There are some important advantages offered by developing apps for macOS and iOS using swift.

  • Open-source language: The Swift programming language has been created as an open-source and is being open to everyone, this makes it simple for the program to upgrade all the source codes, email lists and bug tracker at regular intervals.
  • Easy to learn and maintain: Swift programing language is more simple and accurate when compared to C/C++. Apple evolved its programing language to be easy to use and syntaxes are taken from programming languages such as C#, Python, and Ruby. These simple syntax of this programing language make it more meaningful. In swift, all the content of the implementation (.m) and header (.h) files are combined in a single file that is (.swift).
  • Supported by multiple devices: Swift programming language is not just limited to support Apple devices, it will also support multiple devices of the technology world like Linux and Windows devices.
  • Supports dynamic libraries: Dynamic libraries are the executable chunks of the code that can be connected to an app. This feature allows the latest swift programing language. In swift, dynamic libraries are directly uploaded to the memory, thereby resulting in deduction down on the initial size of the app and finally increases app performance.
  • Optional types: An optional in swift is a type that can be held either as a value or not. To declare an optional, we can use a question “?” mark.
  • Closures: Closures are self-contained blocks of functionality that can be passed around and used in our code.

Q #3) Explain Swift vs Objective-C.

Answer: Enlisted below are the various differences between Swift vs Objective-C.

  1. Swift is an object-oriented and functional programing language, whereas Objective-C is a class-based object-oriented programing language.
  2. Swift supports dynamic libraries, whereas Objective-C does not support dynamic libraries.
  3. Swift supports Tuples, whereas Objective-C does not support Tuples.
  4. Semicolons are not required in Swift, whereas semicolons are required in Objective-C.
  5. Swift is an open-source programing language, whereas Objective-C is limited to Apple, and it’s not an open-source language.
  6. We have to use the “let” keyword to declare for constant and “var” keyword to declare for a variable, whereas in objective C, we have to declare the variable as “NSString” and constant as “int”.
  7. Swift enables us to define methods in structure, classes or enumeration, whereas Objective C does not allow this.
  8. In swift, we can define classes in a single file (.swift), whereas in Objective C we create separate interface (.h) files for classes and implementation (.m) files for classes.

Q #4) Where can we test the apple iPhone apps if we don’t have an iOS device?

Answer: If we don’t have an iOS device, we can test our application on simulators provided by Apple on the Mac system.

Q #5) What are the tools that are required to develop iOS applications?

Answer: These are some of the essential tools that we should have:

  • Mac/MacMini: It is necessary for us to get a Mac with the Intel-based processor running on Mac OS. Not to worry, if we have our own PC, we can still develop iOS apps through Mac Mini.
  • Xcode: Xcode is the Apple IDE (Integrated Development Environment) that is used for both iOS apps and MAC OS. It provides us a visual layout editor and a code editor that can deal with the logic, user interface and response behind the scene.
  • Swift Programming Language: In the code editor, the logic will be written in a programming language that is invented by Apple, called Swift.
  • Apple Developer Program: This program allows the developer to push our app live on the App store so that the customers and downloaders all over the world can download our app and use it.

Q #6) What are the most important features of swift?

Answer: Some important features of swift are given below:

  • More impressive structs and enums
  • Protocol oriented
  • Optional Types
  • Type Safety and Type inference language
  • Not required to use semicolons
  • Enforced initializers
  • Safe by default
  • Less code, fewer files
  • Forced Unwrapping
  • Tuples
  • Closures
  • Much faster when compared to other languages.

Q #7) Explain the common execution states for a swift iOS App (iOS Application Lifecycle).

Answer: The 5 common execution states are as follows:

  • Not Running: This is a simple state in which our app is not launched or no code is being executed and terminated by the system and the application is completely switched off.
  • Inactive: This state is just a transitional state. Inactive state means our application is running in the background but is not able to receive events.
  • Active: Active state is the main execution state, where our app is running in the background and is able to receive events.
  • Background: This is the state where our App is running in the background and still is able to execute the code in the background.
  • Suspended: This state means that our app running is in the background state and the system suspends this app and the application cannot execute any code.

Q #8) Is Swift an object-oriented programming language?

Answer: Yes, swift is an object-oriented programming language.

Q #9) What type of objects are basic data types in swift?

Answer: Swift uses a standard set of basic data types for different purposes such as Boolean values, numbers, and strings.

  • Int: int is used to store the integer value.
  • Double and Float: Double and Float in swift are considered when while working with the decimal numbers.
  • Bool: The bool type is used to store the Boolean value. In swift, it uses true and false conditions.
  • String: In String literals, the user defines the text that is enclosed by double quotes in Swift.
  • Arrays: Arrays are the collection of list items.
  • Dictionaries: A dictionary is an unordered collection of items of a particular type that is connected with a unique key.

Q #10) What is init() in Swift?

Answer: Initialization is a process of preparing an instance of an enumeration, structure or class for use.

Initializers are also called to create a new instance of a particular type. An initializer is an instance method with no parameters. Using the initializer, we can write the init keyword.

init()
{
// perform some New Instance initialization here
}

Q #11) What are the control transfer statements that are used in iOS swift?

Answer: The control transfer statements that are used in iOS swift include:

  1. Return
  2. Break
  3. Continue
  4. Fallthrough

Q #12) What is the difference between Let and Var in swift?

Answer: In swift language, we can declare a constant and variable using Let and Var keyword.

(i) Let: Let keyword is immutable, it’s used to declare a constant variable, and the constant variable cannot be changed once they are initialized.

For Example: let myAge = 25

We cannot change the value of age, you can declare the constant value of it only once using the let keyword.

(ii) Var: Var keyword is mutable, and is used to declare a variant variable. These variant variables can change the run time.

For Example:

var myName = “Dell”

we can change the value of name = “Apple”.

Q #13) How to add an element into an Array?

Answer: Arrays are one of the most used data types in an application (app). We use arrays to organize our application (app) data.

Swift makes it easy to create an array in our code using an array literal. Array elements are simply surrounded by a comma and the list of values is separated with square brackets.

For Example,

// Add ‘Int’ elements in an Array
let natural number = [1, 2, 3, 4, 5, 6, 7]

// Add ‘String’ elements in an array
let countryName = [“India”, “Japan”, “Malaysia”, “Peru”, “Russia”]

Q #14) Which JSON framework is supported by iOS?

Answer: SBJson framework is supported by iOS. SBJson framework provides additional control and a flexible API which makes JSON handling easier. It is a well and highly flexible framework that supports the flexible functioning of APIs.

Q #15) What is PLIST in iOS?

Answer: 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.

Different types of property lists are mentioned below:

  • Binary Property List
  • XML Property List
  • ASCII Legacy Property List

Q #16) What is a dictionary?

Answer: 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.

Syntax of Swift Dictionaries:

Following is the syntax of defining a dictionary in the Swift programming language.

Dictionary<Key, Value> ()

Or

[Key: Value] ()

Creating Dictionaries in Swift:

Following are the different ways of creating a dictionary with key-value pairs in the declaration.

// using Dictionary
Var names = Dictonary<String,Int> ()
Names = [“Ajay”: 1, “Mohit”: 2]
print(names)
// it prints [Ajay: 1, Mohit: 2]

Q #17) What is a Protocol in swift?

Answer: 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.

We can define a protocol in a way that is very similar to structures, enumerations, and classes:

Protocol Someprotocol
{
// protocol definition goes here
}

We can define multiple protocols, which are separated by commas:

Class SomeClass: SomeSuperclass, Firstprotocol, Secondprotocol
{
// Structure definition goes here
}

Q #18) What is a delegate in swift?

Answer: Delegate is a design pattern, which is used to pass the data or communication between structs or classes. Delegate allows sending a message from one object to another object when a specific event happens and is used for handling table view and collection view events.

Delegates have one to one relationship and one to one communication.

Q #19) What is the use of double question mark “??” in swift?

Answer: 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.

Q #20) What is a GUARD statement? What is the benefit of using the GUARD statement in swift?

Answer: 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.

A GUARD statement will be in the following form:

guard condition else
{
Statements
}

Q #21) What are the collection types that are available in swift?

Answer: There are three primary collection types that are available in swift for storing a collection of values. They are dictionaries, sets, and arrays

  1. Arrays: Arrays is an ordered collection of values, which is stored in the same type of values in an ordered list.
  2. Sets: Sets are an unordered collection of unique values, which are stored in a distinct value of the same type in a collection without any defined ordering.
  3. Dictionaries: Dictionaries are an unordered collection of Key and value pair associations in an unordered manner.

Q #22) What is “defer”?

Answer: The “defer” is a keyword that provides a block of code that can be executed while the execution is leaving the current scope.

Q #23) What is Tuple? How to create a Tuple in swift?

Answer: A tuple is a group of different values in a single compound value. It is an ordered list of elements. There are two ways of accessing the object data in a tuple i.e. by name or by position.

In swift, a tuple can consist of multiple different types. It can support two values i.e. one of integer type, and the other of a string type. It is a legal command.

For Example: let ImplementationError = (501, “Not implemented”).

We can create a basic tuple like this:

let person = (name: “Ajay” , age: 34)

Q #24) What is the difference between Array and NSArray?

Answer: 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.

Q #25) What is the difference between class and structure?

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

  1. Classes are reference types, whereas structs are value types.
  2. Classes can be built on other classes, whereas struct cannot inherit from another struct.
  3. Classes have an inheritance, whereas structs cannot have an inheritance.
  4. In class, we can create an instance with “let” keywords and attempt to mutate its property, whereas there is no Mutability in Structs.
  5. Classes have Type Casting, whereas struct doesn’t have Type Casting.

Q #26) What are the best ways of achieving concurrency in iOS?

Answer: The three best way to achieve concurrency in iOS are given below:

  • Dispatch queues
  • Threads
  • Operation queues

Q #27) How to create a constant in Swift programming?

Answer: We have to use the “let” keyword to declare a constant in the Swift Programming.

Q #28) How to pass the data between view controllers?

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

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

Q #29) How can we define a base class in swift?

Answer: In a swift programming language, classes are not inherited from the base class. The classes are defined by the developer without specifying the superclass and it will become the base class automatically.

Q #30) How can we make a property Optional in swift?

Answer: Declaring a Question mark “?” in the swift code can make a property optional. This question mark “?” helps to avoid the runtime error when a property doesn’t hold a value.

Q #31) Who calls the main function of our app during the app launch cycle?

Answer: The main thread calls the main function of our app. During the app launching cycle, the system will create a main thread for the app and call the app main function on that main thread.

Q #32) What are UI elements?

Answer: Images, Buttons, labels, text fields, and any other elements that are visible to the user within the application are called UI elements.

Q #33) Which is the superclass of all the view controller objects?

Answer: UIViewController class is the superclass of all the view controller objects. The functionality for presenting them, loading views, rotating them is a response to the device rotations. All the standard system behavior is provided by the UIViewController class.

Q #34) What are the new feature in Swift 4.0?

Answer: The new features in swift 4.0 are given below:

  • Faster and easier to use strings that keep Unicode correctness.
  • Tuples and multiple return values.
  • Native error handling using throw/try/catch.
  • Extends to support serialization to a struct.

Q #35) How to write a multiple line comment in swift?

Answer: A multiple line comment is written in between the (/*) at the starting point and (*/) at the endpoint.

Q #36) What are the source items used by Xcode?

Answer: Xcode uses four different types of source items as mentioned below:

  • Framework
  • Source Group
  • Source File
  • Source Folder

Q #37) What are the different ways to pass data in swift?

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

Q #38) Explain the usage of Class and benefits of Inheritance.

Answer: They are:

  • Reuse implementation
  • Subclass provides dynamic dispatch.
  • Subclass provides the reuse interface.
  • Modularity
  • Overriding provides the mechanism for customization.

Q #39) Explain some Common features of Protocols & Superclasses.

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

  • Interface reuse.
  • Implementation reuse.
  • Supporting modular design.
  • Provides points for customization.

Q #40) Explain some biggest changes in UserNotifications.

Answer: 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.

Q #41) What is Optional chaining?

Answer: Optional chaining is a useful process which we can use in combination with the optional to call the methods, properties, and subscripts on the optionals and these values may or may not be nil. In this process, we may try to retrieve a value from a chain of the optional values.

  • If the optional contains a value, then calling the subscript, method or property of an optional will return a value.
  • If optional is nil, then calling the subscript, method and property will return nil.

Q #42) What is Optional binding?

Answer: Optional Binding concept is used to find out whether an optional contains a value, and it makes that value available as a variable or temporary constant. We use an optional binding concept to check if the optional contains a value or not.

Optional binding can be used with the condition (if and while) statements to check for a value inside an optional.

Q #43) What are the Higher-Order functions in swift?

Answer: 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.

Q #44) Explain some design patterns which we normally use during the app development.

Answer: The design patterns that are used during app development are given below:

  • Behavioral: Memento, and Observer.
  • Creational: Builder, Factory, and Singleton.
  • Structural: Façade, Adapter, and Decorator.

Q #45) What are the various ways to unwrap an optional in swift?

Answer: 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.

Q #46) What mechanism does iOS support for multi-threading?

Answer: 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.

Q #47) What is Swift module?

Answer:

  • 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.

Q #48) Explain Core Data.

Answer: Core data is one of the most powerful frameworks provided by Apple for macOS and iOS apps. Core data is used for handling the model layer object in our applications. We can treat Core Data as a framework to filter, modify, save, track the data within the iOS apps. Core Data is not a relational database.

Using core data, we can easily map the objects in our app to the table records in the database without knowing any SQL. Core data is the M in MVC structure.

Some features of Core data are given below for your reference:

  • Effective integration with the iOS and macOS toolchains.
  • Organizing, filtering, and grouping data in memory and in the UI (User Interface).
  • Automatic support for storing objects.
  • Automatic validation of property values.
  • First framework for managing an object graph.
  • Core Data framework for managing the life cycle of the object in the object graph.

Q #49) Explain the Grand Central Dispatch (GDC).

Answer: GCD (Grand Central Dispatch) is a low-level API for managing the concurrent operations. This concept is used to help in improving application performance. This process is used to manage multiple tasks at the same time. Grand Central Dispatch (GCD) is the most useful API for multitasking with Async and Sync programming in iOS.

  • Dispatch Queue: The Dispatch Queue manages the task in FIFO(First In First Out) order. Dispatch queues are thread-safe as we can access them from multiple threads simultaneously.
  • Concurrent: This process has started multiple tasks at the same time but is not sure of the termination at the same time. It can be finished in any order. They execute one or more tasks at the same time concurrently. The task is completed according to the complexity, and not by the order in the queue.
  • Serial: Only one task will execute at a time. It can be used to synchronize access to a specific resource.
  • Sync: A synchronous function has return control to the caller after the task is complete.
  • Async: An asynchronous function returns immediately, by ordering the task to start but will not wait for it to complete.

Q #50) Explain MVC structure.

Answer: MVC stands for the model view controller. MVC is a powerful software architecture pattern for using developing apps.

MVC builds on top of the Object-Oriented Programming concepts. It structures the flow of data and interaction in our app. Model-View-Controller is an important fundamental concept to be understood in iOS development. Many iOS frameworks, like UIKit, Cocoa Touch, use the MVC pattern for messaging and structured data flow.

Model-View-Controller is used to pass the data from one part of our app to another.

Its a design pattern used to assign objects in an application in any one of the three roles:

  • Model: Model is a wrapper of data. Model is a representation of our app data and it holds the information to a specific user like birthdate, username, etc. The model manages the application state. This also includes writing and reading data. The Model encapsulates an individual set of data and applies some logic to manipulate that data.
  • View: View is a representation of a UI (User Interface). A View is an object that the visible to the user and it interacts with a user interface (UI).
  • Controller: Controller is an intermediary between the View and the Model. The controller controls all the logic that goes between the Model and the View. Its inter-communicates messages between the Model and the View, and vice versa.