Top 40 iOS Swift Questions Solutions

Yasir
DataDrivenInvestor
Published in
13 min readDec 23, 2020

--

In This Article I have Covered 40 Questions | Swift Programming

1. What is Type Inference ?

In short its an ability of swift . You dont always need to write types of variables and constant you making in your code . For example :

// swift know its Int type
var age = 40 // Int
// You dont need to tell them always like below
var age : Int = 40

2. What is Generics ?

Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.

Understanding it with an example :

Suppose you want to swap to values of type Int , lets write a non-generic functions :

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}var num1 = 4
var num2 = 5
swapTwoInts(&num1 , &num2)

Now , suppose you want to swap two double values or two string values , you will need to write another function for that , because the above function is accepting only for Int type .

What if we have a function which accept any type of values and swap them , this is what generic do .

Now lets do the same thing with a generic function :

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
var num1 = 3
var num2 = 4
swapTwoValues(&num1 , &num2)var str1 = "sdf"
var str2 = "dafdf"
swapTwoValues(&str1 , &str2)

Now you can swap any type of values , you dont need to write different different function to swap different different type of values.

  • T is a placeholder , called as type parameter .

We use array in swift which is also a generic type

  • Array <Element> , Dictionary<Key , Value>

3. What are Protocols ?

Its a blueprint of methods, properties, and other requirements that suit a particular task and it could adopted by a class , structure or enumeration .

Protocol does not include any implementation !!!!

Type which is adopting the protocol , should have all the methods which are present in given protocol . And this action is calledconforming protocol .

Its syntax looks like :

protocol Vehicle {
func accelerate()
func stop()
}class Unicycle : Vehicle {
var peddling = false
func accelerate(){
peddling = true
}
func stop() {
peddling = false
}
}

4. What are Tuples ?

Sometimes data comes in pairs or triplets. An example of this is a pair of (x, y) coordinates on a 2D grid. Similarly, a set of coordinates on a 3D grid is comprised of an x-value, a y-value and a z-value. In Swift, you can represent such related data in a very simple way through the use of a tuple.

let coordinates: (Int, Int) = (2, 3)

5. What about Mutability in Swift ?

Constant(let) are constant in swift and variable(var) varies .

6. What are Subscripts ?

With subscripts you can quickly access the member elements of collections.

A subscript consists of:

  • The name of the collection, such as scores
  • Two square brackets [ and ]
  • A key or index inside the brackets

By default, you can use subscripts with arrays, dictionaries, collections, lists and sequences. You can also implement your own with the subscript function.

subscript(parameterList) -> ReturnType {
get {
// return someValue of ReturnType
}
set(newValue) {
// set someValue of ReturnType to newValue
}

7. What is an Optional ?

Optionals are Swift’s solution to the problem of representing both a value and the absence of a value. An optional is allowed to hold either a value or nil.

8. In what ways you could Unwrap an optional ?

We can unwrap any optional in following ways :

  1. By Optional Binding
  2. By Force Unwrapping
  3. By Guard Statement
  4. By Nil Coalescing

Optional Binding (If let)

Its simplest way to do unwrap an optional .

var authorName : String? = "Mohd Yasir"if let authorName == authorName {
print("Author name is \(authorName)")
else{
print("No Author Name")
}

By Force Unwrapping

To force unwrap , we use “!” .

var authorName : String? = "Mohd Yasir"
print("Auhor name : \(authorName!)")

Guard Statement

Sometimes you want to check a condition and only continue executing a function if the condition is true, such as when you use optionals. Imagine a function that fetches some data from the network. That fetch might fail if the network is down. The usual way to encapsulate this behavior is using an optional, which has a value if the fetch succeeds, and nil otherwise.

Swift has a useful and powerful feature to help in situations like this: the guard statement.

func testingGuard( _ name : String?){
guard let unrappedname = name else {
print("You dont entered any name")
return
}
print("Hello , \(unrappedname)")
}

Nil Coalescing

let name = String? = nil
let unwrappedName = name5 ?? "Unkonwn"

9. What kind of memory allocations takes place in Swift ?

In short Stack and Heap

When you create a reference type such as class, the system stores the actual instance in a region of memory known as the heap. Instances of a value type such as a struct resides in a region of memory called the stack .

10. What is the difference between stack and heap memory ?

  • The system uses the stack to store anything on the immediate thread of execution; it is tightly managed and optimized by the CPU. When a function creates a variable, the stack stores that variable and then destroys it when the function exits. Since the stack is so strictly organized, it’s very efficient, and thus quite fast.
  • The system uses the heap to store instances of reference types. The heap is generally a large pool of memory from which the system can request and dynamically allocate blocks of memory. Lifetime is flexible and dynamic. The heap doesn’t automatically destroy its data like the stack does; additional work is required to do that. This makes creating and removing data on the heap a slower process, compared to on the stack.

11. What is In-Out Parameter ?

Function parameters are constants by default, which means they can’t be modified. To illustrate this point, consider the following code:

func incrementAndPrint(_ value: Int) {  
value += 1
print(value)
}

This results in an error:

Left side of mutating operator isn't mutable: 'value' is a 'let' constant

A behavior known as copy-in copy-out or call by value result. You do it like so:

func incrementAndPrint(_ value: inout Int) {  
value += 1
print(value)
}

inout before the parameter type indicates that this parameter should be copied in, that local copy used within the function, and copied back out when the function returns.

Ampersand (&)

You need to make a slight tweak to the function call to complete this example. Add an ampersand (&) before the argument, which makes it clear at the call site that you are using copy-in copy-out:

var value = 5 
incrementAndPrint(&value)
print(value)

12. What is the difference between synchronous and asynchronous ?

Asynchronous means , you can execute multiple things at a time and you don’t have to finish executing the current thing in order to move on to next one. Synchronous basically means that you can only execute one thing at a time.

13. How you could pass data from one ViewController to another ?

You can pass data between view controllers in Swift in 6 ways:

  1. By using an instance property (A → B)
  2. By using segues (for Storyboards)
  3. By using instance properties and functions (A ← B)
  4. By using the delegation pattern
  5. By using a closures or completion handler
  6. By using NotificationCenter and the Observer pattern

14. What is Completion Handler in Swift ?

A completion handler is a closure (“a self-contained block of functionality that can be passed around and used in your code”). It gets passed to a function as an argument and then called when that function is done.

The point of a completion handler is to tell whatever is calling that function that it’s done and optionally to give it some data or an error. Sometimes they’re called callbacks since they call back to whatever called the function they’re in. Example:

import UIKitlet firstVC = UIViewController()
let nextVC = UIViewController()firstVC.present(nextVC, animated: true, completion: { () in print("Welcome") })

15. What Compiler Swift Uses ?

The Swift compiler uses LLVM .

16. What is Lazy in Swift ?

In simple “A lazy stored property is a property whose initial value is not calculated until the first time it is used.

17. Explain Core Data ?

~AppleDocumentation

  • Its a Framework 💯

Apple Says : “Use Core Data to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device.” 😮

Core data gives you these features : Persistence , Undo and Redo of Individual or Batched Changes , Background Data Tasks , View Synchronization , Versioning and Migration etcc.. .

Creating a Core Data Model

The first step in working with Core Data is to create a data model file. Here you define the structure of your application’s objects, including their object types, properties, and relationships.

You can create core data model while creating project by check the box “use core data” .

Core Data Stack

After you create a data model file , set up the classes that collaboratively support your app’s model layer. These classes are referred to collectively as the Core Data stack .

There are few Core Data Components :

  • An instance of NSManagedObjectModel represents your app’s model file describing your app’s types, properties, and relationships.
  • An instance of NSManagedObjectContext tracks changes to instances of your app’s types.
  • An instance of NSPersistentStoreCoordinator saves and fetches instances of your app’s types from stores.
  • An instance of NSPersistentContainer sets up the model, context, and store coordinator all at once.

Different Data Types in Core Data

Many apps need to persist and present different kinds of information. Core Data provides different attributes, including those common for all databases, such as Date or Decimal type, and non-standard attributes handled with Transformable type.

18. What is Sentinel Value ?

A valid value that represents a special condition such as the absence of a value is known as a sentinel value. That’s what your empty string would be . 🙂

19. Automatic Reference Counting (ARC)

Swift uses ARC to track and manage your app’s memory usage. ARC automatically frees up the memory used by class instances when those instances are no longer needed , you do not needed to think about memory management .

But in few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you .

Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.

I Will PUBLISH an entire article on this topic with more detail !

20. What is nested optional ?

Consider the following nested optional — it corresponds to a number inside a box inside a box inside a box.

21. What are Property observers ?

A willSet observer is called when a property is about to be changed while a didSet observer is called after a property has been changed. Their syntax is similar to getters and setters :

struct S {
var stored: String {
willSet {
print("willSet was called")
print("stored is now equal to \(self.stored)")
print("stored will be set to \(newValue)")
}
didSet {
print("didSet was called")
print("stored is now equal to \(self.stored)")
print("stored was previously set to \(oldValue)")
}
}
}var s = S(stored: "first")
s.stored = "second"
  • willSet was called
  • stored is now equal to first
  • stored will be set to second
  • didSet was called
  • stored is now equal to second
  • stored was previously set to first

22. When would you say that an app is in active state ?

An app is said to be in active state when it is accepting events and running in the foreground.

23. What is the difference between Viewdidload and Viewdidappear ?

  • Viewdidload is called when it is loaded into memory .
  • Viewdidappear is called when the view is visible and presented on the device .

24. What do you meant by Concurrency ?

Concurrency is a condition in a program where two or more tasks are defined independently, and each can execute independent of the other, even if the other is also executing at the same time.

25. Which are the ways of achieving concurrency in iOS ?

The three ways to achieve concurrency in iOS are:

  • Threads
  • Dispatch queues
  • Operation queues

26. What is Thread ?

According to Apple:

“Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi-core computers.”

27. What is Dispatch Queue in Basics ?

According to Apple:

An object that manages the execution of tasks serially or concurrently on your app’s main thread or on a background thread.

28. Difference between Foreground and Background?

The foreground contains the applications the user is working on, and the background contains the applications that are behind the scenes .

29. Classes

Classes are reference types, as opposed to value types . You create a class like :

class Person {
var firstName: String
var lastName: Stringinit(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}

var fullName: String {
return "\(firstName) \(lastName)"
}
}let john = Person(firstName: "Johnny", lastName: "Appleseed")

In Swift, an instance of a structure is an immutable value whereas an instance of a class is a mutable object. Classes are reference types, so a variable of a class type doesn’t store an actual instance — it stores a reference to a location in memory that stores the instance .

Here Comes Stack vs Heap !

When you create a reference type such as class, the system stores the actual instance in a region of memory known as the heap, while instances of a value type such as a struct resides in a region of memory called the stack .

  • The system uses the stack to store anything on the immediate thread of execution; it is tightly managed and optimized by the CPU. When a function creates a variable, the stack stores that variable and then destroys it when the function exits. Since the stack is so strictly organized, it’s very efficient, and thus quite fast.
  • The system uses the heap to store instances of reference types. The heap is generally a large pool of memory from which the system can request and dynamically allocate blocks of memory. Lifetime is flexible and dynamic. The heap doesn’t automatically destroy its data like the stack does; additional work is required to do that. This makes creating and removing data on the heap a slower process, compared to on the stack.

Working with Reference

var homeOwner = john 
john.firstName = "John"
john.firstName // "John"
homeOwner.firstName // "John"

Sharing among class instances results in a new way of thinking when passing things around. For instance, if the john object changes, then anything holding a reference to john will automatically see the update. If you were using a structure, you would have to update each copy individually, or it would still have the old value of “Johnny”.

Identity Operators

Because classes are reference types, it’s possible for multiple constants and variables to refer to the same single instance of a class behind the scenes.

In Swift, the === operator lets you check if the identity of one object is equal to the identity of another:

john === homeOwner // truelet newInstance = Person(firstName: "Johnny",  lastName: "Appleseed")newInstance === John // false

30. What is MVC ?

MVC stands for Model View Controller. Models represent application data; views draw things on the screen; controllers manage data flow between model and view. Model and view never communicate with each other directly and rely on a controller to coordinate the communication.

31. What is @State ?

If you assign @State to a property, SwiftUI will monitor this property and, if it is mutated or changed, will invalidate the current layout and reload.

No need to invoke a refresh call (or a reloadData(), as you might have previously seen in CollectionViews and TableViews).

32. What are Modifiers ?

These are a way of rendering custom interactions and decoration . font(), background(), and clipShape()are the some some examples .

33. What is Nesting Syntax ?

A simple example to that is nesting a list inside a navigation view .

34. What is Grouping in SwiftUI ?

Suppose you have written following code :

VStack {
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}

That works just fine, but if you try adding an eleventh piece of text, you’ll get an error like this one:

ambiguous reference to member 'buildBlock()'

This is because SwiftUIs view building system has various code designed to let us add 1 view, 2 views or 4 , 5 , 6 , 7, 8, 9, and 10 views, but not for 11 and beyond , that doesn’t work .

But we can do this :

var body: some View {
VStack {
Group {
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}
Group {
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}
}
}

That creates exactly the same result, except now we can go beyond the 10 view limit because the VStack contains only two views – two groups.

35. What is Combine ?

Combine is Swift’s own version of Reactive Streams, and it enables objects to be monitored (observed) and data to be passed through streams from core application logic back up to the UI layer .

36. What HashFunction Swifts Dictionary Uses ?

Swift uses the SipHash hash function to handle many of the hash value calculations.

37. What is init() in Swift ?

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

38. What are the control transfer statements that are used in iOS swift ?

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

39. What is a delegate in swift ?

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.

40. What is Optional chaining ?

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.

Where to go from here ?

My LinkedIn : linkedin.com/in/my-pro-file

Check This : https://bit.ly/38k4w7l

In order to Get Connected and Read those useful articles , Follow me Here .

Thank You !
Mohammad Yasir

Gain Access to Expert View — Subscribe to DDI Intel

--

--