50 iOS Interview Questions And Answers Part 2
--
Check out Part 1, if you haven’t already :). Let’s get started.
1- Please explain Method Swizzling in Swift
Method Swizzling is a well-known practice in Objective-C and in other languages that support dynamic method dispatching.
Through swizzling, the implementation of a method can be replaced with a different one at runtime, by changing the mapping between a specific #selector(method) and the function that contains its implementation.
To use method swizzling with your Swift classes there are two requirements that you must comply with:
- The class containing the methods to be swizzled must extend NSObject
- The methods you want to swizzle must have the dynamic attribute
2- What is the difference Non-Escaping and Escaping Closures?
The lifecycle of a non-escaping closure is simple:
- Pass a closure into a function
- The function runs the closure (or not)
- The function returns
Escaping closure means, inside the function, you can still run the closure (or not); the extra bit of the closure is stored someplace that will outlive the function. There are several ways to have a closure escape its containing function:
- Asynchronous execution: If you execute the closure asynchronously on a dispatch queue, the queue will hold onto the closure for you. You have no idea when the closure will be executed and there’s no guarantee it will complete before the function returns.
- Storage: Storing the closure to a global variable, property, or any other bit of storage that lives on past the function call means the closure has also escaped.
for more details.
3- Explain [weak self] and [unowned self] ?
unowned ( non-strong reference ) does the same as weak with one exception: The variable will not become nil and must not be optional.
When you try to access the variable after its instance has been deallocated. That means, you should only use unowned when you are sure, that this variable will never be accessed after the corresponding instance has been…