# SherifKamalSalem / iOS-Interview-Preparation

iOS Interview Preparation.

Geek Repo

Github PK Tool

# iOS Interview Preparation

Objective is to keep this as to date as possible. Advance apologies if some answers are missing. Don't email the author :-]

## Swift Fundamentals

#### What's the difference between mutable and immutable ?

Solution

A mutable object allows for change. An immutable object does not allow for changes.

Mutable object L

```var currentYear = 2020
currentYear = 2021 // could not come fast enough```

Immutable object

```let usIndependenceDay = "July 4th"
usIndependenceDay = "February 22nd" // sorry could not compile, this is 🇱🇨 Independence day```

#### What is a property observer?

Solution

A property observer listens for changes on a object. One can listen for changes when the object is about to get set and when the object actuallly got set.

```var age = 20 {
willSet {
}
didSet {
print("with great power comes great responsibility")
}
}

age = 21

/*
with great power comes great responsibility
*/```

#### What are higher order functions?

Solution

A function that takes another function as an argument or returns a function is said to be a higher order function. This is the fundamental pillar of functional programming.

#### What is recursion?

Solution

A function that calls itself. The two main parts of a recursive function is the base case and the recursive call.

```func jobSearch(_ isHired: Bool) {
// base case
guard !isHired else {
print("Woohoo")
print("Everyone's journey is different")
return
}
// recursive call
print("Job searching...")
jobSearch(Bool.random())
}

jobSearch(false)

/*
Job searching...
Job searching...
Job searching...
Woohoo
Everyone's journey is different
*/ ```

#### Name three built-in protocols in Swift and their use cases?

Solution

`Hashable`. Types conforming to `Hashable` will be guaranteed to be unique.
`CaseIterable`. Enums conforming to `CaseIterable` will make all their cases available and iterable.
`CustomStringConvertible`. Conforming to `CustomStringConvertible` allows a type to override the description property on an object and return a custom String.

#### What's the benefit of an inout function?

Solution

To be able to mutate via referencing the data outside the scope of a function.

#### Write code to access the last element of an array ?

Solution

Example 1:

```let arr = [1, 2, 3, 4]
print(arr[arr.count - 1]) // assuming the array is not empty, will crash otherwise ```

Example 2:

```let arr = [1, 2, 3, 4]
print(arr.last ?? -1) // using nil-coelescing here as last is an optional```

#### What is an optional ?

Solution

In Swift an optional is a type used to indicate that an object can or not have a value.

#### What are Closures ?

Solution

Closures are anonymous functions (functions without a name) that capture references to values in their surrounding context. This is one of the subtle differences between functions and closures. Please note however that nested functions also capture their surrounding values.

```// someFunc definition with a closure parameter
func someFunc(action: (Int, Bool) -> ()) {
let internalValue = 20
action(8 + internalValue, Bool.random()) // the action closure captures the Int and Bool values
}

// someFunc call using trailing closure syntax
someFunc { intValue, boolValue in
print("closure captured values are \(intValue) and \(boolValue)") // closure captured values are 28 and false
}```

#### What is GCD?

Solution

Grand central dispacth is the library that iOS uses to handle concurrency.

#### Name the types of loops available in Swift ?

Solution

while, for-in and repeat-while

#### If using a Command-line macOS application what's the function used for taking user input ?

Solution

For user input or STDIN when working in a command-line application we use `readLine()`.

Solution

O(n)

Solution

O(1)

#### What is the restriction on a dictionary ?

Solution

The keys need to conform to `Hashable`.

#### What is Object Oriented Programming ?

Solution

A paradigm used in programming to represent objects and encapsulate their properties and functions.

```// Parent class
class Person {
var name: String
var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}

func info() {
print("Hi, my name is \(name)")
}
}

// Fellow inherits from the Person class
// Subclass
class Fellow: Person {}

let fellow = Fellow(name: "Xavier Li", age: 23)
fellow.info() // Hi, my name is Xavier Li```

#### What is Protocol Oriented Programming ?

Solution

In Swift this is a paradigm used to describe the blueprint of functions and properties that a conforming object needs to adhere to.

```import UIKit

protocol Vehicle {
var wheels: Int { get }
var color: UIColor { set get }
func drive(speed: Int)
}

struct Bike: Vehicle {
let wheels = 2
var color = UIColor.systemGray

func drive(speed: Int) {
print("current speed is \(speed)")
}
}

let bike = Bike()

bike.drive(speed: 23) // current speed is 23```

#### What is dependency injection?

Solution

Dependency Injection is used to pass all required properties and data over to an object. This is better done through the use on an initializer as the object can fully encapsulate its properties.

Solution

XCTest

#### What is a Singleton?

Solution

A singleton is making use of one instance of a class throughout the life of the launch of an application. One of the main pillars of singleton is the use of marking initializers private so accidental creation of multiple instances is prohibited.

Singletons are used throughout iOS in places like `UserDefaults.standard`, `FileManager.default` and `UIApplication.shared`.

```class GameSession {
static let shared = GameSession()
private init() {
// initialization of properties here
}
}

let session = GameSession.shared

let otherSession = GameSession() // 'GameSession' initializer is inaccessible due to 'private' protection level```

#### Is `URLSession` part of `Foundation` or `UIKit`?

Solution

URLSession is part of the Foundation framework.

#### What's the difference between a compile time error and a runtime error?

Solution

Compile time errors occurs during the writing phase of your code. Runtime erros occurs during the launch and actual use of the application.

#### Is `Index out of range` error on an array an compile-time error or a runtime error?

Solution

`Index out of range` is a runtime error.

#### What's the difference between Structs and Classes?

Solution

Structs are passed-by value (value-types) meaning copies of the objects are passed around thereby making the objects immutable by default. Classes are reference types and their state is easily mutated as objects that have the same reference can make changes at will.

#### Is `NSString` a class or a struct?

Solution

`NSString` is an objective-c API and is a class. With interopobality we can easily bridge between Swift `String` and `NSString`.

#### What's the difference between frames and bounds?

Solution

The frame represents an object's superview and it's relationship in the coordinate space, whereas the bounds represents the objects own size and location.

## iOS Fundamentals

#### What are the two native frameworks used to create user interfaces in iOS?

Solution

UIKit and SwiftUI.

#### What does the `IB` in `IBOutlet` or `IBAction` stand for?

Solution

Interface Builder and NS stands for Next Step in the job process. Reminder to be nice.

#### Name the ways to persist data in iOS ?

Solution

UserDefaults, Documents directory and Core Data.

#### What is ARC ?

Solution

Prior to Automatic reference counting in Objective-C developers needed to keep track of retain and release cycles of objects that were created. With the introduction of ARC now the system does most of the automatic retain/release counting and mememory management for us with limitations such as capturing closures where we need to use weak/unowned as needed.

#### What is MVC?

Solution

No it doesn't stand for massive view controller. 😀

#### What is `URLSession` ?

Solution

The class that manages Networking in iOS.

#### Name three types of gesture recognizers ?

Solution

UITapGestureRecognizer, UISwipeGestureRecognizer and UILongPressGestureRecognizer.

#### Which built-in tool do we use to test performance of our application ?

Solution

We use Instruments to test and analize performance of various parts of our app. Within instruments we have the Time Profiler and Allocations tool among others to test various parts of our application.

#### What is Core Data ?

Solution

Core Data is an object-relatioal graph model of representing and persisting data in an appliation.

#### What is TestFlight and describe its process ?

Solution

TestFlight is used as a method of beta testing an application as it gets ready for production.

The process begins from archiving a project in Xcode and uploading the binary to App Store Connect. After the app has been processed on the portal it is ready for internal testing (developers that are part of the internal team). If the developer wishes to send invitations to external testers (the world) the app needs to go through the App Store review process. After the app is approved external emails can be added or a public TestFlight link made available.

## Tools

#### Name two dependency managers, can you name three ?

Solution

Swift Package Manager, Cocoa Pods and Carthage.

#### What's the difference between `git` and `Github`?

Solution

`git` is an open source versioning system. `Github` is an online versioning platform for project collaboration now owned by Mr. Softie. Other competitors to `Github` are: `BitBucket` and `GitLab`.

#### Describe the ways in which a view can be created ?

Solution

Programmatically, using Storyboard or a xib.

#### What is Continuous Integration (CI) / Continuous Deployment (CD) ?

Solution

Continuous Integration (CI) / Continuous Deployment (CD) is the automation process of connecting your software stack along with testing to ease versioning and deploying software, in our case automatically creating TestFlight builds or App Store builds.

## Networking

#### What are the valid top level types of JSON ?

Solution

The valid top level types are dictionary and array.

#### What is HTTP?

Solution

HTTP is an internet protocol for allowing client/server communication. The client in this case our iOS app makes a request to a Web API / server and gets a response (json) back that we parse (convert) to Swift objects.

#### What is `CRUD` ?

Solution

Create.Read.Update.Delete. This acronym encapsulated the cycle of object creation and modification.

#### Name some HTTP methods ?

Solution

GET, POST, DELETE, PUT, UPDATE.

#### What is a status code and give an example ?

Solution

Status codes are recieved via an http response from a server request to indicate the state and validity of the request. 500 status code implies there's an issue with the server.

#### What are two ways in which web content is formatted for delivery to a client ?

Solution

XML and JSON, the latter being the more popular and easier to understand and parse.

#### Explain RESTFul APIs ?

Solution

REST is an standard architecture that web developers use present data to a client.

#### What is a MIME type ?

Solution

MIME (Multipurpose Internet Mail Extensions) type is a label used to describe the media content of a piece of data.

#### What's the difference between Websockets and HTTP ?

Solution

Websockets allow for a constant two-way stream of data and HTTP transfers data via a request -> response model.

e.g Stock market ticker uses websockets for real time data streaming.

e.g Fetching a new Instagrm photo using http protocol, client request, server response.

## Firebase

#### What are the two types of databases that Firebase supports?

Solution

Firebase realtime database and Firebase firestore.

#### Describe the importance of the `Google-Info.plist` file?

Solution

The `Google-Info.plist` is a property list that encompasses the configurations and connects your Xcode project and Firebase project.

#### What are Firebase rules?

Solution

Firebase rules provides various levels of security on documents and collections in the Firebase database and storage services.