iOS Interview Questions (Swift) — Part 2

For Part 1 follow the link & All About Closure & All About Properties

Animesh Mishra
5 min readMay 5, 2018

--

1. Explain generics in Swift ?

Generics enables you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.

Swift’s Array and Dictionary types are both generic collections.

In below code,generic function for swap two value is used for string and integer. It is the example of reusable code.

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}

var num1 = 4
var num2 = 5
var str1 = “a”
var str2 = “b”

swapTwoValues(&num1,&num2)
swapTwoValues(&str1,&str2)

print (“num1:”, num1) //output: 5
print (“num2:”, num2) //output: 4
print (“str1:”, str1) //output: b
print (“str2:”, str2) //output: a

2. What is optional in swift & when to use optional?

An optional in Swift is a type that can hold either a value or no value. Optional are written by appending a “?” to any type.

Use cases of optional:

1. Things that can fail (I was expecting something but I got nothing)

--

--