General questions Flashcards

1
Q

What is swift? Explain some features

A

Swift, a modern programming language, was announced by Apple Inc. in June 2014.

  • Fast (static dispatch for methods)
  • Safe (type safe)
  • Friendly syntax (more concise than objective-c)

Some key features unique and powerful are : generics, tuples, closures and type inference, optional.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between static typing and dynamic typing?

A

Swift is using Static typing, which is able to give you a compiler error. Objective-C is using dynamic typing, where it performs type checking at run-time. This means that code can compile even if they contain errors that will prevent the script from running properly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is type inference?

A

A feature that enables compiler to automatically set data type on a variable without setting data type, by looking at the value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is generics?

A

A type that can take in any type. It is type safe, meaning that compiler will complain at compile time. For instance, if you pass a string as a generic type and use it as integer, there will be compile-time error. This is good, because you can detect errors beforehand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can objects be nil in Objective-c and Swift?

A

In Objective-c, any object can be nil. In swift, only Optionals can be nil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are protocols?

A

Protocol is an interface, meaning that they contain abstract methods, constants and variables. Protocols enables shared functionality across classes. You can implement multiple protocols.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are tuples?

A
Because they are value types, they are like an immutable array, but the way declared and read is different. They are useful when you want to have multiple return types.
var person = ("Saaya", "Age is secret") 
var firstName = person.0 // Saaya
var lastName = person.1 // Age is secret
To declare, you need a parenthesis (), and to access, you need to give a (.)dot notation.
func getTime() -> (Int, Int, Int) {
    return ( hour, minute, second)
}
var times = getTime()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How is mutability achieved in swift and objective-c?

A

In swift, a constant is a constant, a variable varies. The mutability is defined when initializing a variable with a keyword, not a defined by a data class.
In objective-C, mutability is limited by certain classes. For instance, you have to use NSMutableArray type to be able to change the array size.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between Any Object and Generics?

A

AnyObject does not specify any type, so it will let you pass any type, which might end up in a run-time error(which is bad). When you use generics, you need to specify a type, so it will not let you pass if you input the wrong type at compile-time(which is good).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is an optional?

A

Optional is a type that can store nil value. When it stores a value, it wraps around the value. In order to get the value wrapped in an optional, you need to unwrap it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Write 3 ways to unwrap an optional

A

if-let unwrapping (safe unwrapping)
var myString:String?

if myString != nil {
   print("Value exists!")
}else {
   print("Nil value")
}
guard-if unwrapping (also safe)
var someStr: String?
guard if unwrapped = someStr else { return }
Print (unwrapped)
forced unwrapping (use only when 100% sure there is value)
var someStr: String?
Let unwrapped3 = someStr!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between Struct and Class?

A
Structs are value types, while classes are reference types.
Class
In OOP, a class is a blueprint from which individual instances are created.
A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
We define a class using the class keyword.
Struct
A struct is similar to a class in terms of definition and instance creation.
We define a struct using the struct keyword.
What are the common factors between struct and class?
Define properties to store values
Define methods to provide functionality
Define subscripts to provide access to their values using subscript syntax
Define initializers to set up their initial state
Be extended to expand their functionality beyond a default implementation
Conform to protocols to provide standard functionality of a certain kind
Classes have additional capabilities that structures don’t have:
Inheritance enables one class to inherit the characteristics of another. Struct or enum cannot do inheritance. But they can confirm to protocols.
Type casting enables you to check and interpret the type of a class instance at runtime.
Deinitializers enable an instance of a class to free up any resources it has assigned.
Reference counting allows more than one reference to a class instance.
Since a class is a reference type and it supports inheritance, the complexity increases. In most cases, a struct should be enough to meet your needs. Use a class when they’re appropriate or necessary.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Name two types of data structure for memory allocation

A

Stack and heap memory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the difference between stack and heap memory?

A

Stack is a simple FIFO(first-in-first-out) memory structure. Stack is always used to store the following two things: The reference portion of reference-typed local variables and parameters and the Value-typed local variables and method parameters.
Heap memory has non-lined random objects stored in the memory. The advantage is that it allows objects to be allocated or deallocated in a random order. This will require you to use garbage collectors functions to free the memory though.
In heap memory, the following is stored: the content of reference-typed objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are closures?

A

Self-contained functions organized as blocks. They can be passed around and nested. You can pass a closure as an argument of a function or you can store it as a property of an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is GCD? How is it used?

A

It is a framework provided by apple that deals with multiple threads. It is used when you want to work with asynchronous tasking. For instance, when you want to fetch data from API, you can used GCD to do fetch tasks asynchronously.

17
Q

What is the difference between synchronous and asynchronous tasking?

A

In synchronous tasking, one task doesn’t start until another is finished. In asynchronous tasking, tasks are executed concurrently.

18
Q

What is auto layout?

A

It is a system in xCode that dynamically calculates the size and position of all the views based on constraints placed on those views.

19
Q

What is Core Data? What is the benefit?

A

A native data storage provided by apple enables persistent / permanent storage. It is easy to manage because you can use xcode to change Model name or attributes. It is native so it is very easy to update.

20
Q

Difference and frame and bounds.

A

The bounds of a UIView is the location(x,y) and width(x,y) itself, but the frame of the UIView refers to the superview that UIView is contained.

21
Q

What is a singleton?

A
A design pattern in programming where you can use only one instance for a class. This instance is called “shared instance”. Example:
class Manager{
    static let sharedInstance = Manager()
}
Manager.sharedInstance
22
Q

What is the three basic kind of design patterns?

A

structural
creational
behavioral

23
Q

What is a delegate pattern?

A

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.(apple)

24
Q

What is retain cycle?

A

Retain cycle is the memory structure where strong references of objects are pointing to each other and memory can’t be deallocated. This happens because each object’s reference is lost, but the reference counter still exists.

25
Q

What is a memory leak?

A

Memory that can’t be deallocated. An outcome due to the cause of retain cycle, or forgetting to deinitializing instances.

26
Q

What is ARC?

A
Short for Automatic Reference Counter, a memory manager provided in swift. Also defined as garbage collector. What it does:
releases memory space used as instances that are no longer needed.
memory is allocated when classes are initialized or de-initialized.
keeps track of currently referring class instances (reference count)
27
Q

What is the difference between strong and weak?

A

When you reference an object, it is strong by default in swift. In a strong reference, ARC counts the references for each instances made. This happens when a parent references a child.
To make a weak reference, you need to declare with the weak keyword. Weak is used when a child wants to reference a parent. This is to prevent retain cycle.

28
Q

Which is faster? Array and Set?

A

Set is faster to search because there is only one unique object in the collection. You can directly search for the value in a set, but you have to iterate through the values in an array.

29
Q

SOLID

A

S — Принцип единственной ответственности (The Single Responsibility Principle, SRP)
O — Принцип открытости/закрытости (The Open Closed Principle, OCP)
L — Принцип подстановки Б. Лисков (The Liskov Substitution Principle, LSP)
I — Принцип разделения интерфейса (The Interface Segregation Principle, ISP)
D — Принцип инверсии зависимостей (The Dependency Inversion Principle, DIP)

30
Q

SOLID в iOS разработке. Принцип открытости закрытости

A

Программные сущности (классы, модули, функции и т.п.) должны быть открыты для расширения, но закрыты для изменения
Принцип открытости закрытости позволяет строить систему таким образом, чтобы её легко было масштабировать в будущем, не затрагивая при этом функциональность уже существующих частей. При этом нет необходимости пытаться предусматривать всё заранее. Можно сказать, что это некая рекомендация об изоляции компонентов модулей: чем меньше связаны классы, тем легче менять систему в целом. В то же время, принцип не стоит воспринимать критично, создавая абстракции везде, где только возможно. Наиболее правильная рекомендация: создавать абстракции, только если уже в данный момент понятно, что класс будет нуждаться в расширении.

31
Q

SOLID. Принцип единственной ответственности

A

Каждый класс должен иметь только одну причину для изменения

32
Q

SOLID Concepts

A

Concepts
1. Single responsibility principle: a class should have only a single responsibility (i.e. changes to only one part of the software’s specification should be able to affect the specification of the class).
Open/closed principle: software entities … should be open for extension, but closed for modification.
2. Liskov substitution principle: objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
3. Interface segregation principle: many client-specific interfaces are better than one general-purpose interface.
4. Dependency inversion principle: one should “depend upon abstractions, [not] concretions.”

33
Q

Допустим, у нас есть структура, определяющая модель термометра:

public struct Thermometer {
  public var temperature: Double
  public init(temperature: Double) {
    self.temperature = temperature
  }
}

Чтобы создать экземпляр, мы пишем:

var t: Thermometer = Thermometer(temperature:56.8)

Но было бы гораздо удобнее что-то вроде этого:

var thermometer: Thermometer = 56.8

Возможно ли это? Как?

A

Swift определяет протоколы, которые позволяют инициализировать тип с использованием литералов путем присваивания. Применение соответствующего протокола и обеспечение публичного инициалайзера позволит инициализацию при помощи литералов. В случае Thermometer мы реализуем ExpressibleByFloatLiteral:

extension Thermometer: ExpressibleByFloatLiteral {
  public init(floatLiteral value: FloatLiteralType) {
    self.init(temperature: value)
  }
}

Теперь мы можем создать экземпляр вот так:

var thermometer: Thermometer = 56.8

34
Q

Следующий код определяет структуру Pizza и протокол Pizzeria с расширением для реализации по умолчанию метода makeMargherita():

struct Pizza {
let ingredients: [String]
}

protocol Pizzeria {
  func makePizza(_ ingredients: [String]) -> Pizza
  func makeMargherita() -> Pizza
}
extension Pizzeria {
  func makeMargherita() -> Pizza {
    return makePizza(["tomato", "mozzarella"])
  }
}

Теперь мы определяем ресторан Lombardis:

struct Lombardis: Pizzeria {
  func makePizza(_ ingredients: [String]) -> Pizza {
    return Pizza(ingredients: ingredients)
  }
  func makeMargherita() -> Pizza {
    return makePizza(["tomato", "basil", "mozzarella"])
  }
}

Следующий код создает два экземпляра Lombardis. В котором из них делают маргариту с базиликом?

let lombardis1: Pizzeria = Lombardis()
let lombardis2: Lombardis = Lombardis()

lombardis1. makeMargherita()
lombardis2. makeMargherita()

A

В обоих. Протокол Pizzeria объявляет метод makeMargherita() и обеспечивает реализацию по умолчанию. Реализация Lombardis перекрывает метод по умолчанию. Так как мы объявили метод в протоколе в двух местах, будет вызвана правильная реализация.

А что если бы протокол не объявлял метод makeMargherita(), а extension по-прежнему обеспечивал реализацию по умолчанию, вот так:

protocol Pizzeria {
  func makePizza(_ ingredients: [String]) -> Pizza
}
extension Pizzeria {
  func makeMargherita() -> Pizza {
    return makePizza(["tomato", "mozzarella"])
  }
}

В этом случае только у lombardis2 была бы пицца с базиликом, тогда как у lombardis1 была бы без, потому что он использовал бы метод, определенный в extension.

35
Q

Замыкания — это ссылочный тип или тип-значение?

A

Замыкания — это ссылочный тип. Если вы присваиваете переменной замыкание, а затем копируете в другую переменную, вы копируете ссылку на то же самое замыкание и его список захвата.