Interview Questions and Answers in iOS — Part 7

Interview Questions and Answers in iOS

Q. What is the difference between UIKit and SwiftUI?
A. UIKit
is an imperative event-driven framework for building User Interfaces for the iOS platform. SwiftUI is a declarative framework for building User Interfaces for the Apple platform.

Q. Explain the difference between SceneDelegate and AppDelegate?
A. AppDelegateand SceneDelegate both are part of the UIKit framework. The SceneDelegatetakes over some of the roles from the app delegate with iOS13. The concept of a window is replaced by that of a scene. Multiple scenes allow us to build multi-window apps on iOS and iPadOS.

Q. Please explain application delegate (UIApplicationDelegate) methods introduced in iOS 13?
A.
configurationForConnecting:
According to apple, it returns the configuration data for UIKit to use when creating a new scene.

didDiscardSceneSessions: This method is called as an app’s user closed one or more scenes via the app switcher.

// MARK: UISceneSession Lifecyclefunc application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration 
{
//Called when a new scene session is being created.
//Use this method to select a configuration to create the new
scene with.
return UISceneConfiguration(name: "Default Configuration",
sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>)
{
//Called when the user discards a scene session.
//If any sessions were discarded while the application was not
running, this will be called shortly after
application:didFinishLaunchingWithOptions.
//Use this method to release any resources that were specific to
the discarded scenes, as they will not return.
}

For more details please check this link.

Q. UISceneDelegate?
A. Introduced in iOS 13. With the introduction of UISceneDelegate, the background and foreground lifecycle methods of UIApplicationDelegate won’t be called. That means the code in these methods won’t run:

  • applicationDidBecomeActive
  • applicationWillResignActive
  • applicationDidEnterBackground
  • applicationWillEnterForeground

The app delegate will still receive the willFinishLaunchingWithOptions: and didFinishLaunchingWithOptions: method calls so any code in those methods will work as before.

Here are the core methods of UISceneDelegate.

  • scene(_:willConnectTo:options:) It’s most similar to the role of the application(_:didFinishLaunchingWithOptions:) function of UIApplicationDelegate. This function is called when a scene is added to the app, so it’s the perfect point to configure that scene.
  • sceneDidDisconnect(_:) is called when a scene has been disconnected from the app (Note that it can reconnect later on.)
  • sceneDidBecomeActive(_:) is called when the user starts interacting with a scene, such as selecting it from the app switcher.
  • sceneWillResignActive(_:) is called when the user stops interacting with a scene, for example by switching to another scene.
  • sceneWillEnterForeground(_:) is called when a scene enters the foreground, i.e. starts or resumes from a background state.
  • sceneDidEnterBackground(_:) is called when a scene enters the background, i.e. the app is minimized but still present in the background.

The UIApplicationDelegate equivalent functions of UISceneDelegate for Swift:

Q. opaque return types (some) in swift?
A. Introduced in Swift 5.1. It means “one specific sort of view, but we don’t really care what.”

Q. What is the @State property wrapper?
A. @State
variables are owned by the view(struct). @State property wrapper allows us to modify values inside a struct, which would normally not be allowed because structs are value types.

Q. What is the @Binding property wrapper?
A.
As we learned above, State properties must always relate to a specific View. But sometimes we want to have access to a State property from the outside, for example from child views. For creating such a reference, we use the @Binding property wrapper.

Q. What’s the difference between @State, @ObservedObject, and @EnvironmentObject?
A.
-
We use @State for simple properties that belong to a single view. They should usually be marked as private.
- We use @ObservedObject for complex properties that might belong to several views(class). Any time we’re using a reference(class) type we should use @ObservedObject for it.
- We use @EnvironmentObject for properties that were created elsewhere in the app, such as shared data.

Q. What is UIStackView?
A. UIStackView provides a way to layout a series of views horizontally or vertically. We can define how the contained views adjust themselves to the available space. Don’t miss this article.

Q. How can you prevent a user from doing said action more than once on their device?
A.
Apple has introduced DeviceCheck in iOS 10. This API allows us to access per-device, per-developer data in an iOS device. The solution is better than UserDefaults or Advertising Identifier. DeviceCheck allows us to store a boolean value.

Q. Please explain Associatedtype?
A.
If we want to create a Generic Protocol we can use associatedtype. For more details check this out.

Q. What is unwind segue?
A.
An unwind segue is a type of segue used to implement backward navigation.

Q. Fallthrough keyword in swift?
A. In Swift,switch statement completes its execution as soon as the first matching case is completed.
In swift, the fallthrough statement is used in switch cases to execute a case statement which is next to the matched case statements based on our requirements.

var index = 10switch index {
case 100 :
print("Value of index is 100.")
fallthrough
case 10,15 :
print("Value of index is either 10 or 15.")
fallthrough
case 5 :
print("Value of index is 5.")
default :
print("default case.")
}
Output:
Value of index is either 10 or 15.Value of index is 5.

Q. Explain subscripts?
A. Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.

Like functions, subscripts can use Variadic Parameters and Default Parameter Values. However, unlike functions, subscripts can’t use in-out parameters.

Just like methods and free functions, Swift subscripts can be overloaded to provide different functionality for a different set of inputs.

subscript (<parameters>) -> <return type> {
get { // the getter is required
// used for subscript value declarations
}
set(newValue) { // the setter is optional
// definitions are written here
}
}
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
Example: 1
struct
TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"
Example: 2
class daysOfAWeek {
private var days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
subscript(index: Int) -> String {
get {
return days[index]
}
set(newValue) {
self.days[index] = newValue
}
}
}
var p = daysOfAWeek()

print(p[0]) = Sunday
print(p[1]) = Monday
print(p[2]) = Tuesday
print(p[3]) = Wednesday

Instance subscripts, as described above, are subscripts that we call on an instance of a particular type. We can also define subscripts that are called on the type itself. This kind of subscript is called a Type subscript.

enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
static subscript(n: Int) -> Planet {
return Planet(rawValue: n)!
}
}
let mars = Planet[4]
print(mars)

Link 1, Link 2, Link 3

Q. What is NSZombie?
A. It’s a memory debugging aid. Specifically, when we set NSZombieEnabled then whenever an object reaches retain count 0, rather than being deallocated it morphs itself into an NSZombie instance. Whenever such a zombie receives a message, it logs a warning rather than crashing or behaving in an unpredictable way. As such, we can debug subtle over-release/autorelease problems.
or
NSZombie is a memory debugging aid that helps us to debug subtle over-release/autorelease problems.

Q. SOLID Principles?
A. SOLID is an acronym for 5 important design principles when doing OOP (Object Oriented Programming). The five principles are:
S: Single responsibility principle: Classes should have a single responsibility and thus only a single reason to change.
O: Open/closed principle: Classes and other entities should be open for extension but closed for modification.
L: Liskov substitution principle: Objects should be replaceable by their subtypes.
E.g: If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.
I: Interface segregation principle: Interfaces should be client-specific rather than general.
D: Dependency inversion principle: Depend on abstractions rather than concretions.
OR
High-level modules should not depend on low-level modules. Both should depend on the abstraction.
Abstractions should not depend on details. Details should depend on abstractions.

Q. What is UIViewRepresentable?
A. UIViewRepresentable is a wrapper for a UIKit’s UIView subclasses that we use to integrate any UIView subclass into our SwiftUI view hierarchy.

Q. Explain CAEmitterLayer and CAEmitterCell?
A.
UIKit provides two classes for creating particle effects: CAEmitterLayer and CAEmitterCell.
The CAEmitterLayer is the layer that emits, animates, and renders the particle system.
The CAEmitterCell represents the source of particles and defines the direction and properties of the emitted particles.

Q. Closed Range Operator (lowerBound…upperBound)?
A.
The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
E.g: 1...3 Defines range containing values 1,2,3

// 1...3 Defines a range containing values 1, 2 and 3
for value in 1...3 {
print(value)
}
Output:
1
2
3

Q. Half Open Range Operator (lowerBound..<upperBound)?
A.
The half-open range operator (a..<b) defines a range that runs from a to b, but doesn’t include b.
E.g: 1..<3 Defines range containing values 1 and 2

// 1..<3 Defines a range containing values 1,2
for value in 0..<3 {
print(value)
}
Output:
0
1
2

Q. One-Sided Range Operator?
A.
One-sided range is those types of the range that continue as far as possible in one direction.
It can be created using both half-open range operator and closed range operator but the operator can have a value on only one side.

let names = ["Anna", "Alex", "Brian", "Jack"]for name in names[2...] {
print(name)
}
// Brian
// Jack
for name in names[...2] {
print(name)
}
// Anna
// Alex
// Brian
for name in names[..<2] {
print(name)
}
// Anna
// Alex

Q. Why we use return true or false in App Delegate’s method application(_:didFinishLaunchingWithOptions:)?
A.
false if the app cannot handle the URL resource or continue a user activity, otherwise return true. The return value is ignored if the app is launched as a result of a remote notification.

Q. Difference Between UIWebView and WKWebView?
A.
- WKWebView
introduced by iOS 8.0 whereas UIWebView was introduced by iOS 2.0

- The UIWebView is a part of UIKit and available inside Interface Builder (applications) so no need to import anything — it’s just there only drag and drop of UIWebView will work for the design whereas WKWebView is run in a separate process so need to import to the application.

- The UIWebView uses the UIKit framework while WKWebView uses WebKit.framework.

- The WKWebView loads web pages faster and more efficiently than UIWebView and also doesn’t have as much memory overhead for us.

- Scale pages to fit — this feature is available in UIWebView but not available in WKWebView.

- The WKWebView has some extra support than UIWebView like IndexedDB and ObjectStore ArrayBuffer.

- The WKWebView renders about 8500 objects while UIWebView renders about 3500 objects and WKWebView’s performance is twice good as compared to UIWebView.

- In iOS 8.0 WKWebView was unable to load local files, but this got fixed in iOS 9.0. but this feature is available in UIWebView.

- The UIWebView load only once and the data will be stored in cookies so that the next loading time will be less than the previous time whereas no cookies will get saved in WKWebView so it will always be the same loading time.

Q. How swift is Protocol Oriented Programming Language?
A.
At WWDC 2015, Apple announced that Swift is the world’s first Protocol-Oriented Programming (POP) language.

Protocol-Oriented Programming is a new programming paradigm used by Apple in Swift 2.0. In the Protocol-Oriented approach, we start designing our system by defining protocols. We rely on new concepts: protocol extensions, protocol inheritance, and protocol compositions.

Swift supports multiple paradigms: Object-Oriented Programming, Protocol Oriented Programming, and Functional Programming. What does this mean to us, software developers? The answer is FREEDOM. It’s up to us which paradigm to choose.

Q. Difference between Object-Oriented and Protocol-Oriented Programming?
A.
OOP relies on inheritance and POP relies on protocols.

Q. Explain Result Type?
A.
The result type is implemented as an enum that has two cases: success and failure callbacks. Result has four other methods: map(), flatMap(), mapError(), and flatMapError(). Each of these gives us the ability to transform either success or error.

Q. Explain Asset Catalogs?
A.
We use asset catalogs to store images such as icons or images. Since iOS 11, we can store named colors in asset catalogs. Another lesser-known feature of asset catalogs is that we can store arbitrary data assets. With iOS 13 now we can define dark mode icons and images.

Q. Explain OptionSet?
A.
Option sets are similar to enums, but OptionSet designs to work more than one at a time. We can say enums are an exclusive state, OptionSet is an inclusive state. For creating an OptionSet, there is one requirement which is the rawValue the property of integer type, and an initializer. Option sets aren’t collections.

Q. Explain Thread Sanitizer?
A.
Enabling Thread Sanitizer allows us to debug data races when multiple threads try to access the same memory area in a nonatomic way and with at least one write operation in one of those threads.

Thread Sanitizer is only supported for 64-bit macOS and 64-bit iOS and tvOS simulators. watchOS is not supported.

Thread Sanitizer | Apple Developer Documentation

Q. Explain Address Sanitizer?
A.
Address Sanitizer watches memory corruption and buffers overflows. It works for both the Simulator and on devices after a recompilation. We can also use compiler optimization level of None [-O0] or at most Fast [-O1].

We can enable it when running unit and UI tests.

Q. App Store Connect API?
A.
App Store Connect API was announced in WWDC 2018. App Store Connect API is a standard RESTful API. API used JSON Web Tokens for authentication and can be accessed from all platforms.

We can automate managing certificates, provisioning profiles, managing device ID and bundle ID, users, roles, TestFlight, and Public Links.

Q. CodingKey Protocol?
A.
The CodingKeys enum ( Protocol ) lets us rename specific properties in case the serialized format doesn’t match the requirements of the API. CodingKeys should have nested enum.

Q. Main Thread Checker?
A.
The Main Thread Checker is a new tool launched with Xcode 9 which detects the invalid use of Apple’s frameworks like UIKit, AppKit, etc that supposed to be used from the main thread but accidentally used in the background thread. The effect of invalid usage can result in missed UI updates, visual defects, data corruption, and crashes. We can read more about the Main Thread Checker here.

Q. UIBezierPath?
A.
UIBezierPath class, allows us to define custom paths that describe any shape and use those paths to achieve any custom result we want.

Q. Explain the difference between Generics and AnyObject in Swift?
A.
Generics are type-safe, meaning if we pass a string as a generic and try to use it as an integer the compiler will complain and we will not be able to compile our code. Because Swift is using Static typing and is able to give us a compiler error.

If we use AnyObject, the compiler has no idea if the object can be treated as a String or as an Integer. It will allow us to do whatever we want with it.

Q. Size of launch screen?
A.
In iOS 14 and later, the launch screen is limited to 25 MB.

Q. What is the @objc attribute in swift?
A.
We use this attribute to make our code(class and method) available to Objective-C as well as Swift code.

To expose a method to Objective-C, just write @objc before its name like this:

class MyController: UIViewController {
@objc func authenticateUser() {
}
}

That whole class is automatically Objective-C friendly because it inherits from UIViewController, but if we need it we can also explicitly make a class open to Objective-C by marking it @objc .

Q. Designated Initializers and Convenience Initializers?
A.
In Swift, “Initialization is the process of preparing an instance of a class, structure, or enumeration for use.

Example: 1 & Source: Apple
Example: 2 & Source: Apple

Designated Initializers
-
Designated initializers are the primary initializers for a class.
- They have to fully initialize all the properties introduced by that class.
- They must also call a designated initializer from their immediate superclass (then up the chain of classes)
- Classes will typically have one designated initializer, but can easily have more.
- Every class must have at least one designated initializer.
- The chain of delegating initializers will end with a call to a non-delegating initializer.
In some cases, this requirement is satisfied by inheriting one or more designated initializers from a superclass because of Automatic Initializer Inheritance.

init(sender: String, recipient: String) {
self.sender = sender
self.recipient = recipient
super.init()
}

Convenience Initializers
-
Secondary, supporting initializers for a class.
- They’ve got to call a designated init from the same class.
- We don’t need these but they can help to widen our options.
- We can define a convenience initializer to create an instance of our class for a particular use-case or input value type.
- Place the convenience word before init to make one of these.
- These can be shortcuts to common initialization patterns

convenience init() {
self.init(sender: "X", recipient: "Y")
}

To recap then:
- A Designated Initializer must call a Designated Initializer from its immediate superclass.
- A Convenience Initializer must call another initializer from the same class.
- A Convenience Initializer has to ultimately call a designated initializer.

A simple way to remember this is:
- Designated initializers must always delegate up.
- Convenience initializers must always delegate across.

Q. Memberwise Initializers?
A.
Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers.

Q. Difference between Class and Structure in Swift?
A.
-
Structures are value types, and classes are reference types.
- Inheritance is only present in classes.
- Memberwise initializers are present only in structures.

Q. How Reference and Value types are stored in memory?
A.
Value Type:
Get Stored on Stack Memory.
Reference Type: Get Stored on Managed Heap Memory.

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM.

For reference types, the reference is stored on the stack while the object it refers to is stored on the heap. For value types, the object itself is stored on the stack.

Since reference types are always stored on the heap, anything they contain (even value types) is also stored on the heap. For ex: If a class has a struct instance inside it, then the struct instance will be stored in the heap along with the class instance.

In short: Reference types always go to the Heap, whereas Value Types always go where they are declared.

Important Links:
https://abhimuralidharan.medium.com/difference-between-value-type-and-a-reference-type-in-ios-swift-18cb5145ad7a

Q. Property Wrapper?
A.

- The @propertyWrapper annotation is available in Swift 5.1 or later.
- A property wrapper is a generic structure that encapsulates read and write access to the property and adds additional behavior to it.
- We use it if we need to constrain the available property values, add extra logic to the read/write access (like using databases or user defaults), or add some additional methods like value validation.
- Property wrapper can be implemented using either a struct or a class by annotating it with the @propertyWrapper attribute. Besides that, the only real requirement is that each property wrapper type should contain a non-static stored property called wrappedValue.
- The @propertyWrapper annotation provides one more syntax sugar - a projected value. This property can have any type we want. To access this property, we need to add a $ prefix to the property name.
- Limitations: They can’t participate in error handling, and applying multiple wrappers to the property is not allowed.

Q. Why can’t we override a function in an extension in Swift?
A.
Function/Methods we write in extension invoked using the static dispatch mechanism and that is why we cannot override a function/method in extension.

For More Details:
https://medium.com/@m.muizzsuddin_25037/override-protocol-extension-default-implementation-in-swift-969753f4b11b

For More about Method Dispatch in Swift:
https://www.rightpoint.com/rplabs/switch-method-dispatch-table

Q. What is the difference between protocol and delegate?
A.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol.

Delegation: Acting on Behalf of Another Object(Design pattern in oops)
Protocol: Enabling Communication Between Objects Not Related by Inheritance

Q.

Thank you for reading! If you liked this article, please clap to get this article seen by more people.
Please follow me on Medium by clicking Follow.
I’m also active on LinkedIn, Twitter, and GitHub.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store