Interview - 10 questions about Swift. Part 3

Original author: Animesh Mishra
  • Transfer

Professional program “iOS Developer” - 5 months Best Practice for developing mobile applications using Swift 5. The best graduates are expected at interviews of 12 OTUS partner companies, therefore we publish a translation of the final article from the series “iOS Interview Questions (Swift)”, where we will consider more dozens of questions, the answers to which will help you with employment.


1. What are faults and where can they be used?

  • Closures are self-contained code fragments that can be passed to a function as an argument or used in a program.
  • Closures in Swift are like blocks in C and Objective-C and like lambdas in other programming languages.
  • This is almost the same as functions, but closures do not have to be named.
  • There is no need to declare the type of each parameter, but if you do, then you do not need to specify the type of the return value.

Follow the link to see all closure syntax options.

2. What are escaping / nonescaping closures?

@nonescaping (standard) closures:

  • When the closure is passed in the arguments of the function and and is used before the body of the function is executed and control returns.
  • When the function completes , the passed closure goes out of scope and no longer exists in memory.

@escaping (runaway) closures:

  • When the closure is passed in the function arguments and used after the function body is executed and control returns.
  • When the function completes , the transmitted closure continues to exist in scope and remains in memory until the closure is completed. link

3. Indicate what types of collections are available in Swift?


  • Arrays - used to store several values ​​of the same type in an ordered form.
  • Set (Set) - used to store different values ​​of the same type in an unordered form.
  • Dictionaries - Used to store key-value pairs in an unordered form.

4. How is the base class defined in Swift?

In Swift, classes that do not inherit from the base class, and classes that you define without specifying a superclass, automatically become base classes.

5. What are deinitializers and how are they written in Swift?

The de-initializer is declared immediately before freeing the memory occupied by the class instance. The deinitializer is written with the keyword deinit . It is used if you need to perform any action or cleanup before freeing the memory occupied by the object.

For example , if you create a custom class to open a file and write some data to it, you will need to close the file before freeing the memory occupied by the class instance.

The deinitializer is written without brackets and does not accept any parameters.

deinit {
// выполняем деинициализацию

6. When are double question marks “??” used?

This operator is called the nil join operator . It is used to set the default value if the option is nil.

let a: String? = nil
let b = "nil coalescing operator"
let result = a ?? b
print(result) //вывод:"nil coalescing operator"

  • a ?? b decompresses optional a if it contains a value, or returns the default value b if a is nil.
  • The expression a always has an optional type. The expression b must match the type that is stored inside a.

6. What is the difference between '?' And '!'?

The symbol "?"

  1. When working with options, you can put “?” In front of sets of commands such as methods, properties, and subscripts.
  2. If the value before "?" Is nil, then everything that comes after "?" Is ignored, and the value of the whole expression becomes nil.
  3. Otherwise, the option is unpacked, and everything that comes after the “?” Acts on the unpacked value.
  4. In both cases, the value of the entire expression is optional.

The symbol "!"

  1. After making sure that the optional contains a value, you can access its base value by adding an exclamation mark (!) At the end of the optional name.
  2. The exclamation point actually says: “I know that this option really matters; please use it. ”
  3. Use it only if you are absolutely sure that the implicitly unpacked option is important the first time you access it.

7. What is a type alias in Swift?

A type alias declaration introduces a named alias of an existing type into the program. Type alias declarations are declared using the typealias keyword.

typealias name = existing type

typealias StudentName = String
let name:StudentName = "Jack"

You can use typealias for most types in Swift, for example:

  • Built-in types (e.g. String, Int)
  • Custom types (e.g. classes, structures, enumerations)
  • Complex types (e.g. closures)

8. What is the difference between functions and methods in Swift?

A method is a function associated with a class, structure, or enumeration. This applies to both instance methods and type methods.

Function - declared in the global scope and does not belong to any type.

Функции могут быть определены вне классов или внутри классов/структур/перечислений, в то время как методы должны быть определены внутри и быть частью классов/структур/перечислений.

9. Какой синтаксис у внешних параметров?

Внешний параметр позволяет нам давать имена параметрам функции, чтобы сделать их назначение более понятным.

func power(base a: Int, exponent b: Int) -> Int

*Иногда бывает полезно назвать каждый параметр при вызове функции, чтобы указать назначение каждого аргумента, который передается функции.

Если вы хотите, чтобы пользователи вашей функции указывали имена параметров при ее вызове, определите имя внешнего параметра для каждого параметра в дополнение к имени локального параметра.*

10. Можно ли переопределять структуры и перечисления в Swift?

You cannot subclass a structure or enumeration, nor can you override them. Because the structure is a type of value, and the compiler needs to know its exact size at compile time, which overriding makes impossible.

To find the previous parts, follow the links Part 1 , Part 2 , All about closures , All about properties

That's all! We are sure that translations will be useful not only to students of the iOS Developer course , but also to many Habr users. We wish you professional success and look forward to the next groups of our copyrighted online programs!

Also popular now: