50 Swift iOS Most Asked Interview Question Answers.
50 Swift iOS Most Asked Interview Question Answers.
Basic Swift Questions
What are the main differences between
varandletin Swift?vardeclares a variable that can be changed, whileletdeclares a constant that cannot be changed after initialisation .
Explain the difference between
structandclassin Swift.structis a value type (copied when assigned), whileclassis a reference type (shared reference when assigned).
What is an optional in Swift, and how do you unwrap it?
- An optional is a type that can hold either a value or
nil. It is unwrapped using!,if let,guard let, or optional chaining.
- An optional is a type that can hold either a value or
What is the purpose of
guardstatement in Swift?guardis used for early exits in a function or method if certain conditions are not met. It ensures conditions are met before proceeding.
How does Swift handle memory management?
- Swift uses Automatic Reference Counting (ARC) to manage memory, automatically deallocating objects when they are no longer needed.
What is a tuple in Swift, and how do you use it?
- A tuple groups multiple values into a single compound value. It is accessed by index or by name if specified.
Explain what
deferdoes in Swift.deferschedules code to be executed just before the function returns, useful for cleanup tasks.
What is the difference between
Array,Set, andDictionaryin Swift?Arrayis an ordered collection of elements,Setis an unordered collection of unique elements, andDictionaryis a collection of key-value pairs.
What are computed properties in Swift?
- Computed properties provide a getter and optionally a setter to calculate a value, rather than storing a value directly.
What is the use of the
lazykeyword in Swift?lazyinitialises a property only when it's accessed for the first time, which can improve performance if the property is not always needed.
Intermediate Swift Questions
What is the difference between
map,filter, andreducein Swift?maptransforms each element in a collection,filterreturns elements that satisfy a condition, andreducecombines elements into a single value.
Explain how
extensionswork in Swift.extensionsadd new functionality to existing classes, structs, enums, or protocols without modifying the original source code.
What is the purpose of
Protocolin Swift?- A
protocoldefines a blueprint of methods, properties, and other requirements for types to conform to, enabling polymorphism.
- A
How do you achieve method overloading in Swift?
- Method overloading is achieved by defining multiple methods with the same name but different parameters (type, number, or order).
What is an enum, and how can it be used in Swift?
- An
enumdefines a common type for a group of related values, often used for type safety and better code organization.
- An
How do you create a singleton in Swift?
- A singleton is created by defining a static constant instance of the class, which is accessed globally.
class MySingleton {static let shared = MySingleton() private init() {} }Explain the difference between
escapingandnon-escapingclosures in Swift.escapingclosures are called after the function returns, while non-escaping closures must be called before the function returns.
What is optional chaining in Swift?
- Optional chaining allows you to safely access properties and methods on an optional that might currently be
nil.
- Optional chaining allows you to safely access properties and methods on an optional that might currently be
How does error handling work in Swift?
- Swift uses
do-catchblocks withthrowstatements to handle errors, enabling the graceful handling of potential runtime issues.
- Swift uses
What are key paths in Swift, and how are they used?
- Key paths allow you to refer to a property of a type in a type-safe way, often used for accessing properties dynamically.
Advanced Swift Questions
What are property wrappers in Swift?
- Property wrappers are a way to add behavior to properties by defining custom logic that runs when properties are accessed or modified.
How do you use generics in Swift?
- Generics allow you to write flexible and reusable functions and types that work with any data type.
func swap<T>(_ a: inout T, _ b: inout T) {let temp = a a = b b = temp }Explain the difference between
weak,unowned, andstrongreferences in Swift.weakreferences do not keep a strong hold and can benil,unownedreferences do not keep a strong hold and cannot benil, whilestrongreferences keep a strong hold on an object.
What is the significance of
Codablein Swift?Codableis a type alias for theEncodableandDecodableprotocols, used to easily encode and decode data to and from JSON.
What are
associated typesin Swift protocols?- Associated types allow a protocol to define a placeholder name for a type that is used as part of the protocol.
What is
typealias, and how is it used in Swift?typealiasis used to create a new name for an existing type, making code more readable or to simplify complex type declarations.
Explain what
Resulttype is and how it is used in Swift.Resultis an enum that represents either a success (.success) or failure (.failure) outcome, used for handling asynchronous operations.
How does
dispatchwork in Swift, and what is GCD?- Grand Central Dispatch (GCD) is a low-level API for managing concurrent code execution, using dispatch queues to handle tasks asynchronously or synchronously.
What is
NSCopying, and how does it work in Swift?NSCopyingis a protocol that requires implementing acopy(with:)method to provide a copy of an object.
What are
@objcanddynamickeywords used for in Swift?@objcexposes Swift APIs to Objective-C, anddynamicis used for dynamic dispatch, allowing methods to be replaced at runtime.
iOS Development-Specific Questions
What is the difference between
UIViewandUIViewController?UIViewrepresents a rectangular area on the screen, whileUIViewControllermanages a set of views and the logic to control them.
How do you handle memory leaks in Swift?
- Memory leaks are handled by avoiding retain cycles, using
weakorunownedreferences, and understanding ARC.
- Memory leaks are handled by avoiding retain cycles, using
Explain what Auto Layout is and how it works.
- Auto Layout is a system for defining the constraints that govern the size and position of views, ensuring a responsive UI across different screen sizes.
How does
NotificationCenterwork in Swift?NotificationCenteris used for broadcasting information across different parts of an app, allowing observers to react to events.
What are delegates and how do they work in Swift?
- Delegates are a design pattern that allows one object to act on behalf of, or in coordination with, another object.
What is the difference between synchronous and asynchronous tasks in Swift?
- Synchronous tasks block the current thread until the task is completed, while asynchronous tasks run in the background, allowing the thread to continue executing.
How do you implement a
UITableViewin Swift?- A
UITableViewis implemented by setting up a data source and delegate, providing cells withcellForRowAtand handling selection withdidSelectRowAt.
- A
What is Core Data, and how is it used in Swift?
- Core Data is a framework for managing an object graph and persistence, allowing you to save, retrieve, and manage model objects.
Explain the Model-View-Controller (MVC) design pattern in Swift.
- MVC divides an application into three interconnected components: the model (data), the view (UI), and the controller (logic), each responsible for different aspects of the application.
What is Combine, and how is it used in Swift?
- Combine is a reactive programming framework that allows you to process values over time, often used for handling asynchronous events in a declarative way.
Code-Specific and Conceptual Questions
How would you use closures to filter an array in Swift?
- You can use a closure with the
filtermethod to return only the elements that satisfy a certain condition.
let numbers = [1, 2, 3, 4, 5]let evenNumbers = numbers.filter { $0 % 2 == 0 }- You can use a closure with the
Explain how Swift handles multithreading.
- Swift handles multithreading using GCD and
OperationQueue, allowing tasks to be executed concurrently or serially on different threads.
- Swift handles multithreading using GCD and
What is a
mutatingfunction in Swift, and when would you use it?- A
mutatingfunction can modify the properties of a struct or an enum, used when a value type needs to change its internal state.
- A
How would you create a custom protocol in Swift, and what are its uses?
- A custom protocol defines a blueprint of methods, properties, or other requirements that a class, struct, or enum must conform to.
protocol Drivable {func drive() }What is a
subscriptin Swift, and how do you implement it?- A
subscriptallows you to access elements of a collection, list, or sequence like an array.
struct TimesTable {let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } }- A
How do you manage dependencies in a Swift project?
- Dependencies in Swift are often managed using tools like CocoaPods, Carthage, or Swift Package Manager.
Explain how Swift’s
type inferenceworks.- Swift automatically infers the type of a variable or constant based on the value assigned to it, reducing the need for explicit type annotations.
How do you create a custom operator in Swift?
- Custom operators are created using the
operatorkeyword, followed by defining the operator's behaviour.
infix operator +++func +++(left: Int, right: Int) -> Int { return left + right + 3 }- Custom operators are created using the
What is the difference between
@escapingand@autoclosurein Swift?@escapingallows a closure to be called after the function it was passed to returns, while@autoclosureautomatically creates a closure from an expression passed to a function.
How would you implement dependency injection in Swift?
- Dependency injection is implemented by passing dependencies into a class, struct, or enum at initialization time, typically using initializer injection or property injection.
Comments
Post a Comment