⬆️ ⬇️

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<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 


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:



A property that may be present or absent , for example, middle name or husband / wife in the class Person.



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 nothing , for example, try to read the contents of a file (as a result, the file data will usually be returned), but the file does not exist.



Delegate properties that do not always have to be set and are usually set 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?



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



An optional sequence returns two values ​​-

The optional sequence is an alternative to forced unpacking.



What is forced unwrapping?



Forced unpacking is a way to retrieve the value contained in an option. 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! //  newValue  1 let anotherOptionalInt: Int? = nil let anotherInt = anotherOptionalInt! // Output:fatal error:  nil    . 


What is implicit unwrapping?



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



 var name: String! = β€œVirat” let student = name //       name = nil let player = name //Output:fatal error:  nil    . 


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 -  ( )   // ,   possibleString print(actualString) } else { //possibleString   ,   // } 


What is the Guard and what are its advantages?



The operator guard is 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 { 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"]) //  "Added Ravi!" //  "roll No not assigned" addStudent(student: ["name": "Ravi", "rollNo": "1"]) //  "Added Ravi!" //  "Assigned roll no is 1" 


The advantage of guard is faster execution . Guard block is executed only if the condition is false, and the block is exited through a 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 ?





What is defer ?



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



The defer inside the if block will be executed first. Then follows the LIFO template to execute the remaining defer statements.



 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”)} }  1<2 6 5 4 3 2 1 


List which control transfer operators are used in Swift?



break - The break statement immediately terminates the entire control flow statement.



continue - the continue statement tells the loop to stop what it is doing, and to start over at the beginning of the next iteration of the loop.

return - returns values ​​from functions.

throw - need probros errors using Throwing Functions

fallthrough - The 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.



In swift the fallthrough operator fallthrough used to execute the next 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” fallthrough case 10: description += β€œ case 10.” default: description += β€œ an integer.” } print(description)// :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.

Source: https://habr.com/ru/post/452806/



All Articles