Set_3 Flashcards
What is Cocoa?
Cocoa and Cocoa Touch are the application development environments for OS X and iOS, respectively. Both Cocoa and Cocoa Touch include the Objective-C runtime and two core frameworks:
Cocoa, which includes the Foundation and AppKit frameworks, is used for developing applications that run on OS X.
Cocoa Touch, which includes Foundation and UIKit frameworks, is used for developing applications that run on iOS.
What is inout parameter?
All parameters passed into a Swift function are constants, so you can’t change them. If you want, you can pass in one or more parameters as inout, which means they can be changed inside your function, and those changes reflect in the original value outside the function. func doubleInPlace(number: inout Int) {
Difference between weak self vs unowned self?
The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around.
The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.
What is tuple?
Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call. You can create a basic tuple like this: let person = (name: "Paul", age: 35)
When to use delegate or closures?
We can say that delegate callbacks are more process oriented and closure are more results oriented. If you need to be informed along the way of a multi-step process, you’ll probably want to use delegation. If you just want the information you are requesting (or details about a failure to get the information), you should use a closure.
a. If an object has more than one distinct event, use delegation.
b. If an object is a singleton, we can’t use delegation.
c. If the object is calling back for additional information, we’ll probably use delegation.
Can we declare variables in protocol and does Protocol support extension?
Yes, The protocol doesn’t specify whether the property should be a stored property or a computed property — it only specifies the required property name and type.
protocol SomeProtocol { var one: Int { get set } var two: Int { get } } Yes, You can extend an existing type to adopt and conform to a new protocol, even if you don’t have access to the source code for the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and are therefore able to add any requirements that a protocol may demand.
What is Optional Chaining?
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil. if let johnsStreet = john.residence?.address?.street { print(“John’s street name is \(johnsStreet).”) } else { print(“Unable to retrieve the address.”) }
Difference between delegates and closures? Which one to prefer?
Ans: First of all, there is nothing that is impossible without using closures. You can always replace a closure by an object implementing a specific interface. It’s only a matter of brevity and reduced coupling.
Comparison
1. Length and Relationship
The closure way is shorter. When you work with the delegate way, you have to implement the required functions to conform to the protocol.When you use the closure way, even if the object calls the method, Class can simply ignore. Therefore, the closure way is often called, “decoupled”. The relationship is rather weak and fragile.
Some would argue that you can make the delegate function as “optional”. But, if you see your code , it still looks complicated.
2. Memory Management
When it comes to memory management, you have to define the protocol as class and define the delegate property as weak to prevent retain cycle.
When you work with the closure way, you have to define self either withunowned or weak. If you are not using self, you don’t have to worry about retain cycle.
3. Backward Communication
If you want to communicate back to the object, using the delegate way, you have to use the datasource pattern. If you want to communicate back to the object using the closure way, you also have to return something in closure.
Well, there isn’t much difference.
4. Dryness
If you want to implement many other delegate protocols, you probably have to include all protocol and implement methods, which looks hideous and you will have a hard time tracking and debugging. Good luck. Yes, we’ve tried to manage and distribute through extension but it will still be tough my friend.
But when it comes to the closure way, it wins.
Even other platforms are moving from delegate to closure way, React and React Native use the closure way.
Опишите циклические ссылки в Swift? Как их можно исправить?
Циклические ссылки происходят, когда два экземпляра содержат сильную ссылку друг на друга, что приводит к утечке памяти из-за того, что ни один из этих экземпляров не может быть освобождён. Экземпляр не может быть освобождён, пока есть еще сильные ссылки на него, но один экземпляр держит другой.
Это можно разрешить, заменив на одной из сторон ссылку, указав ключевое слово weak или unowned.
Как настроить Live Rendering?
Атрибут @IBDesignable позволяет Interface Builder обновлять конкретные элементы.
Чем отличаются синхронная и асинхронная задача?
Синхронная: ждет, пока задача завершится. Асинхронная: завершает задачу в фоновом режиме и уведомляет вас о завершении.
Что такое b-деревья?
Это поисковые деревья, которые предоставляют упорядоченное хранилище ключевых значений с отличными характеристиками производительности. Каждый узел хранит отсортированный массив своих собственных элементов и другой массив для своих дочерних элементов.
Что такое объект NSError?
Существует три части объекта NSError: домен, код ошибки и словарь с пользовательской информацией. Домен — это строка, которая идентифицирует, к какой категории относится эта ошибка.
Что такое Enum?
Enum – это тип, который в основном содержит группу связанных значений.
В чем разница strong, weak, read only и copy?
Атрибуты свойства strong, weak, assign определяют, как будет управляться память для этого свойства.
Strong означает, что в сгенерированном сеттере счетчик ссылок на присваиваемый объект будет увеличен и ссылка на него будет поддерживаться в течение жизни объекта.
Weak означает, что мы указываем на объект, но не увеличиваем счетчик ссылок. Он часто используется при создании родительских-дочерних отношений. Родитель имеет сильную ссылку на ребенка, но ребенок имеет только слабую ссылку на родителя.
Read only — мы можем установить свойство изначально, но затем его нельзя будет изменить.
Copy означает, что мы копируем значение объекта при его создании. Также предотвращает изменение его значения.