iOS Swift Questions
What is Protocol Extensions?
We can adopt protocols using extensions as well as on the originalΒ type declaration. This allows you to add protocols to types you donβtΒ necessarily own.
Why do we use availability attributes ?
Apple wants to support one system version back, meaning that we should support iOS9 or iOS8. Availability Attributes lets us to support previous version iOS.
Whatβs the difference optional between nil and .None?
There is no difference. Optional.None (.None for short) is theΒ correct way of initializing an optional variable lacking a value,Β whereas nil is just syntactic sugar for .None.
How do you follow up clean code for this project ?
I follow style guide and coding conventions for Swift projects of Github and SwiftLint.
How many different ways to pass data in Swift ?
There are many different ways such as Delegate, KVO, Segue, and NSNotification, Target-Action, Callbacks.
When do you use optional chaining vs. if let or guard ?
We use optional chaining when we do not really care if the operationΒ fails; otherwise, we use if let or guard. Optional chaining lets us runΒ code only if our optional has a value.
Using the question mark operator like this is called optional chaining. Appleβs documentation explains it like this:
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.
Could you explain Associatedtype ?
If you want to create Generic Protocol we can use associatedtype. For more details check this out.
What is the difference Filter and Map Function ?
Map, we pass in a function that returns a value for each element inΒ
an array. The return value of this function represents what an elementΒ
becomes in our new array.
Filter, we pass in a function that returns either true or false forΒ
each element. If the function that we pass returns true for a givenΒ
element, then the element is included in the final array.
What is DispatchGroup ?
DispatchGroup allows for aggregate synchronization of work. We canΒ
use them to submit multiple different work items and track when they all
Β complete, even though they might run on different queues. This behavior
Β can be helpful when progress canβt be made until all of the specifiedΒ
tasks are complete.
Explain subscripts ?
Classes, structures, and enumerations can define subscripts, whichΒ
are shortcuts for accessing the member elements of a collection, list,Β
or sequence.
What is Nil Coalescing & Ternary Operator ?
nil coalescing - ??
teranry - ? :
It is an easily return an unwrapped optional, or a default value. If we do not have value, we can set zero or default value.
What is the Swift main advantage ?
To mention some of the main advantages of Swift:
Optional Types, which make applications crash-resistant.
Built-in error handling.
Closures.
Generics, Protocol Extensions and Constraints make it easy to reuse code and implement new functionality.
Faster in execution when using best practices (Slower in compilation).
Type-safe language.
Supports pattern matching.
More human readable code.
What is the difference CollectionViews & TableViews ?
TableViews display a list of items, in a single column, a vertical fashion, and limited to vertical scrolling only.
CollectionViews also display a list of items, however, they can have multiple columns and rows.
What is Alamofire doing ?
Alamofire uses URL Loading System in the background, so it doesΒ
integrate well with the Apple-provided mechanisms for all the networkΒ
development. This means, It provides chainable request/response methods,
Β JSON parameter and response serialization, authentication, and manyΒ
other features. It has thread mechanics and execute requests on aΒ
background thread and call completion blocks on the main thread.
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 an 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 deallocated.
However, if you donβt want the variable to be weak AND you are sureΒ
that it canβt be accessed after the corresponding instance has beenΒ
deallocated, you can use unowned.
Every time used with non-optional types
Every time used with let
By declaring it [weak self] you get to handle the case that it might beΒ
nil inside the closure at some point and therefore the variable must beΒ
an optional. A case for using [weak self] in an asynchronous networkΒ
request, is in a view controller where that request is used to populateΒ
the view.
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Β
specificselector(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
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 some place 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.
Explain generics ?
Generics create code that does not get specific about underlying data types.
Generics allow us to know what type it is going to contain.
Generics provide code reusability.
Explain lazy ?
An initial value of the lazy stored properties is calculated onlyΒ
when the property is called for the first time. There are situationsΒ
when the lazy properties come very handy to developers.
Explain what is defer ?
defer keyword which provides a block of code that will be executed in the case when execution is leaving the current scope.
What is Enum ?
βORβ Type. Enum represents a group of all possible values the Object can represent.
What is Operator Overloading ?
Operator overloading allows us to change how existing operators behave with types that both already exist.
How to pass a variable as a reference ?
We need to mention that there are two types of variables: referenceΒ
and value types. The difference between these two types is that byΒ
passing value type, the variable will create a copy of its data, and the
Β reference type variable will just point to the original data in theΒ
memory.
To pass value type as a reference we use &valueTypeVariable as anΒ
inout parameter in the function.
Please explain Swiftβs pattern matching techniques
Tuple patterns are used to match values of corresponding tuple types.
Type-casting patterns allow you to cast or match types.
Wildcard patterns match and ignore any kind and type of value.
Optional patterns are used to match optional values.
Enumeration case patterns match cases of existing enumeration types.
Expression patterns allow you to compare a given value against a given expression.
Please explain final keyword ?
By adding the keyword final in front of the method name, we prevent the method from being overridden. Can substitute final class
keyword with a single word static
and get the same behavior.
Final classes canβt be subclassed
What is the difference open
& public
access level ?
open allows other modules to use the class and inherit the class; for
Β members, it allows others modules to use the member and override it.
public only allows other modules to use the public classes and theΒ
public members. Public classes can no longer be subclassed, nor publicΒ
members can be overridden.
What is the difference fileprivate
, private
and public private(set)
access level ?
fileprivate is accessible within the current file, private is accessible within the current declaration.
public private(set) means getter is public, but the setter is private.
What is Internal access ?
Internal access enables entities to be used within any source fileΒ
from their defining module, but not in any source file outside of theΒ
module.
Internal access is the default level of access. So even though weΒ
havenβt been writing any access control specifiers in our code, our code
Β has been at an internal level by default.
Explain Forced Unwrapping
When we defined a variable as optional, then to get the value fromΒ
this variable, we will have to unwrap it. This just means putting anΒ
exclamation mark at the end of the variable.
Explain Swift Standard Library Protocol ?
There are a few different protocol. Equatable protocol, that governsΒ
how we can distinguish between two instances of the same type. ThatΒ
means we can analyze. If we have a specific value is in our array. TheΒ
comparable protocol, to compare two instances of the same type andΒ
sequence protocol: prefix(while:) and drop(while:) [SE-0045].
Swift 4 introduces a new Codable
protocol that lets us serialize and deserialize custom data types without writing any special code.
Explain Swift Package Manager
The Swift Package Manager will help to vastly improve the SwiftΒ
ecosystem, making Swift much easier to use and deploy on platformsΒ
without Xcode such as Linux. The Swift Package Manager also addressesΒ
the problem of dependency hell that can happen when using manyΒ
interdependent libraries.
The Swift Package Manager only supports using the master branch.Β
Swift Package Manager now supports packages with Swift, C, C++ andΒ
Objective-C.
How is an inout parameter different from a regular parameter?
An Inout is passed as function parameter.
Inside a function the local copy is modified
Before function returns it takes inout
object and sets itβs value equal to that local copy
So it seems like you pass parameter by reference, however itβs not actually the case
What are benefits of Guard ?
There are two big benefits to guard. One is avoiding the pyramid ofΒ
doom, as others have mentionedβββlots of annoying if let statementsΒ
nested inside each other moving further and further to the right. TheΒ
other benefit is provide an early exit out of the function using breakΒ
or using return.