Interview – 10 questions about Swift. Part 2

There is less time left before the launch of the iOS Developer Course, so today we continue to publish material from the 10 Questions About Swift series. The first part of which can be read here.

Explain the generics in Swift?

Generics (generic templates) allow you to write flexible, reusable functions and types that can work with any type. You can write code that avoids duplication and expresses its purpose in a clear, abstract manner.

The Array and Dictionary types in Swift are generic collections (generics).
In the code below, the universal function for the swap of two values ​​is used for a string and an integer. This is sample reusable code.

func swapTwoValues(_ 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

What are the optional types in swift and when should they be used?

Optional (Optional, “optional”) in Swift is a type in which the value may or may not be. Options are indicated by adding a “?” To any type.

Options for using the optionals:

  1. Code snippets that might fail (I was expecting something, but I didn't get anything).
  2. Objects that are currently empty but may become something later (and vice versa).

A good example of the option is:

Property that may or may not be presentFor example, patronymic or husband / wife in Person class.

A method that can return either a value or nothing.for example, matching in an array.

A method that can return either a result or get an error and return nothingfor example, trying to read the contents of a file (as a result of which the file data will usually be returned), but the file does not exist.

Delegate propertieswhich should not always be installed and usually installed after initialization.

Like weak links in classes. What they indicate can be set to nil at any time.

If you need a way to find out when a value is set (data not yet loaded> data) instead of using a separate dataLoaded logical variable.

What is an optional sequence (optional chaining) in Swift?

Query processes, invoking properties, subscripts, and methods for an optional, which can be "nil", is defined as an optional sequence (optional string).

An optional sequence returns two values ​​-

  • if the optional contains a “value”, then when calling its associated properties, methods, and subscripts, the value is returned
  • if the optional contains “nil”, all properties, methods and subscripts associated with it return nil

The optional sequence is an alternative to forced unpacking.

What is forced unwrapping?

Forced unpacking Is a way extraction values ​​contained in the optionals. This operation is dangerous because you are essentially telling the compiler: I am sure that this optional contains 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: sudden nil when unpacking an optional value.

What is implicit unwrapping?

Implicit unpacking: when we define an implicitly unpacked optional, we define a container that will automatically force an unpack every time we read it.

var name: String! = “Virat”
let student = name // Currently we are reading the text
name = nil
let player = name // Output: fatal error: Sudden nil when unpacking an optional value.

If an implicitly unpacked option is nil and you try to access its packed value, you will cause a runtime error. The result is exactly the same as if you placed an exclamation point after the usual optional, which does not contain a value.

What is optional binding?

You can unpack optionals in a “safe” or “unsafe” way. The safe way is to use optional binding.

The optional binding is used to find out if the optional contains a value, and if so, we will make that value available as a time constant or variable. Thus, there is no need to use the suffix! to access its value.

let possibleString: String? = "Hello"
if let actualString = possibleString {
// actualString is a normal (not optional) string value
// equal to the value stored in possibleString
   print (actualString)
else {
  // possibleString do not contain value, process this
  // situation

What Guard and what are its benefits?

Operator guard simple and powerful. It checks a condition and, if it is evaluated as false, the else statement is executed, which usually terminates the method.

func addStudent (student: [String: String]) {
guard let name = student["name"] else {
print ("Added  (name)!")
guard let rollNo = student ["rollNo"] else {
print ("roll No not assigned")
print ("Assigned roll no is  (rollNo).")
addStudent (student: ["name": "Ravi"])
// Displays "Added Ravi!"
// Displays "roll No not assigned"
addStudent (student: ["name": "Ravi", "rollNo": "1"])
// Displays "Added Ravi!"
// Displays "Assigned roll no is 1"

Advantage guard lies in more fast performance. Guard the block is executed only if the condition is false, and the block is exited through the control transfer operator, such as return, break, continue or thrown. This provides an early exit and fewer brackets. Early exit means faster execution.

Please refer to this article for more information.

When to use guard let, and when if let?

  • Use guardwhen you want to eliminate unexpected / incorrect input and focus on the goal if you have alternative ways to handle input.
  • Use guard if else block to reduce nesting and indentation, as it is relatively compact.

What defer?

Operator defer used to execute a set of statements immediately before code execution leaves the current block.

Operator defer inside block if will be executed first. Then follow the LIFO template to perform the rest defer operators.

func doSomething () {
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")}
Conclusion 1 <2 6 5 4 3 2 1

List which control transfer operators are used in Swift?

break – operator break Immediately terminates the entire control flow statement.

continue – operator continue tells the loop to stop what it is doing and start over at the beginning of the next iteration of the loop.
return – returns values ​​from functions.
throw – you need to forward errors using Throwing Functions
fallthrough – operator fallthrough used in a switch case block to execute a case statement that is next to the corresponding case statements based on user requirements.

AT swift operator fallthrough is used to execute the following case, even if it does not match the original one.

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”
case 10:
description + = “case 10.”
description + = “an integer.”
print (description) // Output: The number 5 is a prime number, and also case 10.

The end of the second part. The first part can be read here.

We are waiting for your comments and remind you that in a few hours there will be an open door, which will tell you in detail about our course.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *