Sie sind auf Seite 1von 7

22.09.

2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

iOS Interview Questions (Swift) —


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

Animesh Mishra
May 5, 2018 · 5 min read

1. Explain generics in Swift ?

G enerics 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.
https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 1/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

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)

2. Things that are nothing now but might be something later (and vice-versa)

Good example of optional:

A property which can be there or not there, like middleName or spouse in a Person
class.

A method which can return a value or nothing, like searching for a match in an array.

A method which can return either a result or get an error and return nothing, like
trying to read a file’s contents (which normally returns the file’s data) but the file doesn’t
exist.

Delegate properties, which don’t always have to be set and are generally set after
initialization.
https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 2/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

For weak properties in classes. The thing they point to can be set to nil at any time.

When you need a way to know when a value has been set (data not yet loaded > the data)
instead of using a separate dataLoaded Boolean.

3. What is optional chaining in swift?

The process of querying, calling properties, subscripts and methods on an


optional that may be ‘nil’ is defined as optional chaining. Optional chaining return
two values −

if the optional contains a ‘value’ then calling its related property, methods and
subscripts returns values

if the optional contains a ‘nil’ value all its its related property, methods and
subscripts returns nil

Optional chaining is the alternative of forced unwrapping.

4. What is forced unwrapping?

F orced Unwrapping : It’s the way of extracting the value contained inside an
Optional. This operation is dangerous because you are telling the compiler: I am
sure this Optional value does contain a real value, extract it!

let value: Int? = 1

let newValue: Int = value! // Now newValue contains 1

let anotherOptionalInt: Int? = nil

let anotherInt = anotherOptionalInt! // Output:fatal error: unexpectedly found nil


while unwrapping an optional value.

5. What is implicit unwrapping?

I
read it.
mplicit Unwrapping : When we define an Implicitly unwrapped optional, we
define a container that will automatically perform a force unwrap each time we

var name: String! = “Virat”

https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 3/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

let student = name // If now we read text

name = nil

let player = name //fatal error: unexpectedly found nil while unwrapping an
Optional value

If an implicitly unwrapped optional is nil and you


try to access its wrapped value, you’ll trigger a
runtime error. The result is exactly the same as if
you place an exclamation mark after a normal
optional that doesn’t contain a value.
6. What is Optional binding ?

You can unwrap an optional in both a “safe” and “unsafe” way. The safe way is to use
Optional Binding.

Optional binding used to find out whether an optional contains a value, and if so, to
make that value available as a temporary constant or variable. There’s no need to use
the ! suffix to access its value.

let possibleString: String? = "Hello"


if let actualString = possibleString {
// actualString is a normal (non-optional) String value
// equal to the value stored in possibleString
print(actualString)
}
else {
// possibleString did not hold a value, handle that
// situation
}

7. What is Guard statement and its benefits?

G
a method.
uard statement is simple and powerful. It checks for some condition and if it
evaluates to be false, then the else statement executes which normally will exit

https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 4/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

func addStudent(student: [String: String]) {


guard let name = student["name"] else {
return
}
print("Added \(name)!")
guard let rollNo = student ["rollNo"] else {
print("roll No not assigned")
return
}
print("Assigned roll no is \(rollNo).")
}

addStudent(student: ["name": "Ravi"])


// Prints "Added Ravi!"
// Prints "roll No not assigned"

addStudent(student: ["name": "Ravi", "rollNo": "1"])


// Prints "Added Ravi!"
// Prints "Assigned roll no is 1"

B enefit of guard statement is faster execution. A guard block only runs if the
condition is false, and it will exit out of the code block through a control transfer
statement like return , break , continue , or thrown . It provides an early exit and fewer

brackets. Early exit means faster execution.

Please refer this article for more about optional.

8. When to use guard let and if let?

Use guard when we want to eliminate unexpected/incorrect input and focus on


purpose and use if when we have alternative ways to handle input.

Use guard if else block is relatively short to reduce nesting and indentation.

9. What is defer ?

D efer statement to execute a set of statements just before code execution leaves
the current block of code.

The defer statement inside the if code block will be executed first. Then it follows a
LIFO pattern to execute the rest of the defer statements.

func doSomething() {

https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 5/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

defer { print(“1”)}

defer { print(“2”)}

defer { print(“3”)}

if 1<2 {

defer { print("1<2")}

defer { print(“4”)}

defer { print(“5”)}

defer { print(“6”)}

Output 1<2 6 5 4 3 2 1

10. List out what are the control transfer statements used in Swift?

break — The break statement ends execution of an entire control flow statement
immediately

continue — The continue statement tells a loop to stop what it is doing and start
again at the beginning of the next iteration through the loop.

return — returns values from functions.

throw —used in propagating errors Using Throwing Functions

fallthrough — fallthrough statement is used in switch case to execute case


statements which is next to the matched case statements based on our
requirements.

In swift, fallthrough statement is used to execute next switch case statement event if it is
not matching.

let integerToDescribe = 5
var description = “The number \(integerToDescribe) is”
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += “ a prime number, and also”
https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 6/7
22.09.2019 iOS Interview Questions (Swift) — Part 2 - Animesh Mishra - Medium

fallthrough
case 10:
description += “ case 10.”
default:
description += “ an integer.”
}
print(description)// Output:The number 5 is a prime number, and also
case 10.

For other parts follow the link Part1 & Part3..All About Closure & All
About Properties

Swift Objective C iOS iOS App Development Swift Programming

About Help Legal

https://medium.com/@anios4991/ios-interview-questions-swift-part-2-d3a070f9dbd 7/7

Das könnte Ihnen auch gefallen