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
var
andlet
in Swift?var
declares a variable that can be changed, whilelet
declares a constant that cannot be changed after initialisation .
Explain the difference between
struct
andclass
in Swift.struct
is a value type (copied when assigned), whileclass
is 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
guard
statement in Swift?guard
is 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
defer
does in Swift.defer
schedules code to be executed just before the function returns, useful for cleanup tasks.
What is the difference between
Array
,Set
, andDictionary
in Swift?Array
is an ordered collection of elements,Set
is an unordered collection of unique elements, andDictionary
is 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
lazy
keyword in Swift?lazy
initialises 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
, andreduce
in Swift?map
transforms each element in a collection,filter
returns elements that satisfy a condition, andreduce
combines elements into a single value.
Explain how
extensions
work in Swift.extensions
add new functionality to existing classes, structs, enums, or protocols without modifying the original source code.
What is the purpose of
Protocol
in Swift?- A
protocol
defines 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
enum
defines 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
escaping
andnon-escaping
closures in Swift.escaping
closures 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-catch
blocks withthrow
statements 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
, andstrong
references in Swift.weak
references do not keep a strong hold and can benil
,unowned
references do not keep a strong hold and cannot benil
, whilestrong
references keep a strong hold on an object.
What is the significance of
Codable
in Swift?Codable
is a type alias for theEncodable
andDecodable
protocols, used to easily encode and decode data to and from JSON.
What are
associated types
in 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?typealias
is used to create a new name for an existing type, making code more readable or to simplify complex type declarations.
Explain what
Result
type is and how it is used in Swift.Result
is an enum that represents either a success (.success
) or failure (.failure
) outcome, used for handling asynchronous operations.
How does
dispatch
work 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?NSCopying
is a protocol that requires implementing acopy(with:)
method to provide a copy of an object.
What are
@objc
anddynamic
keywords used for in Swift?@objc
exposes Swift APIs to Objective-C, anddynamic
is used for dynamic dispatch, allowing methods to be replaced at runtime.
iOS Development-Specific Questions
What is the difference between
UIView
andUIViewController
?UIView
represents a rectangular area on the screen, whileUIViewController
manages 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
weak
orunowned
references, 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
NotificationCenter
work in Swift?NotificationCenter
is 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
UITableView
in Swift?- A
UITableView
is implemented by setting up a data source and delegate, providing cells withcellForRowAt
and 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
filter
method 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
mutating
function in Swift, and when would you use it?- A
mutating
function 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
subscript
in Swift, and how do you implement it?- A
subscript
allows 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 inference
works.- 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
operator
keyword, 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
@escaping
and@autoclosure
in Swift?@escaping
allows a closure to be called after the function it was passed to returns, while@autoclosure
automatically 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