Top Swift Interview Questions
Are you preparing for a Swift developer interview? Whether you’re a beginner or an experienced professional, mastering Swift is essential for iOS development. In this guide, we have compiled the Top 100 Swift Interview Questions with detailed answers and examples. These questions cover fundamental concepts, advanced techniques, and best practices to help you ace your Swift interview. Read on to boost your Swift programming knowledge and stay ahead of the competition!
Top 100 Swift Interview Questions
1. What is Swift? How is it different from Objective-C?
Swift is a powerful, open-source, and type-safe programming language developed by Apple for iOS, macOS, watchOS, and tvOS applications.
Key Differences:
Feature | Swift | Objective-C |
---|---|---|
Syntax | Clean and concise | Verbose and complex |
Type Safety | Strongly typed | Weakly typed |
Memory Management | Automatic (ARC) | Requires manual handling |
Interoperability | Works with Objective-C | Cannot use Swift directly |
Example in Swift:
var message = "Hello, Swift!"
print(message) // Output: Hello, Swift!
2. What are the key features of Swift?
- Type-safe and concise syntax
- Memory management with Automatic Reference Counting (ARC)
- Optionals to handle
nil
values safely - Protocol-oriented and functional programming support
- Error handling using
do-catch
3. What is type inference in Swift?
Swift automatically detects the data type without explicitly defining it.
Example:
var age = 25 // Swift infers as Int
var name = "John" // Swift infers as String
4. What are optionals in Swift? Why are they used?
Optionals allow variables to have a nil (no value) state, preventing runtime crashes.
Example:
var username: String? = nil // Optional variable
username = "Alice"
print(username!) // Force unwrapping
5. What is forced unwrapping in Swift?
Using !
to extract values from an optional variable. If the variable is nil
, it causes a crash.
Example:
var age: Int? = 25
print(age!) // Output: 25
✅ Safer Alternative: Use Optional Binding (if let
)
if let validAge = age {
print(validAge)
}
6. What is optional binding in Swift?
It safely extracts the value of an optional using if let
or guard let
.
Example:
var email: String? = "test@example.com"
if let validEmail = email {
print("Email is \(validEmail)")
}
7. What is optional chaining?
It safely accesses properties of optional variables using ?
.
Example:
class Person {
var name: String?
}
var person: Person? = Person()
person?.name = "Alice"
print(person?.name ?? "No name") // Output: Alice
8. What is a tuple in Swift?
A tuple is a collection of multiple values of different types.
Example:
let user = (id: 101, name: "John", isActive: true)
print(user.name) // Output: John
9. What are the different collection types in Swift?
- Array – Ordered collection of elements
- Set – Unordered collection with unique values
- Dictionary – Key-value pairs
Example:
var fruits = ["Apple", "Banana", "Cherry"] // Array
var uniqueNumbers: Set = [1, 2, 3] // Set
var studentGrades = ["Alice": 90, "Bob": 85] // Dictionary
10. What is a dictionary in Swift? How do you access its values?
A dictionary stores key-value pairs, and values are accessed using keys.
Example:
var userInfo = ["name": "Alice", "age": "25"]
print(userInfo["name"] ?? "Unknown") // Output: Alice
11. What are computed properties in Swift?
A property that dynamically computes its value.
Example:
class Circle {
var radius: Double = 5.0
var area: Double {
return 3.14 * radius * radius
}
}
let circle = Circle()
print(circle.area) // Output: 78.5
12. What is the difference between let
and var
?
Keyword | Mutability | Example |
---|---|---|
let | Immutable (constant) | let pi = 3.14 |
var | Mutable (variable) | var age = 25 |
13. What is a closure in Swift?
A closure is a self-contained block of code that can be passed around as a function parameter.
Example:
let greet = { (name: String) -> String in
return "Hello, \(name)!"
}
print(greet("Alice")) // Output: Hello, Alice!
14. What are higher-order functions in Swift?
Functions that accept another function as a parameter or return a function.
Examples:
map
– Transforms each element in a collectionfilter
– Filters elements based on a conditionreduce
– Combines all elements into a single value
let numbers = [1, 2, 3, 4, 5]
// Using `map`
let squared = numbers.map { $0 * $0 }
print(squared) // Output: [1, 4, 9, 16, 25]
// Using `filter`
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4]
15. What is the difference between struct
and class
in Swift?
Feature | Struct | Class |
---|---|---|
Mutability | Immutable by default | Mutable |
Memory | Stored in stack (value type) | Stored in heap (reference type) |
Inheritance | ❌ No inheritance | ✅ Supports inheritance |
Example:
struct Car {
var brand: String
}
var car1 = Car(brand: "Toyota")
var car2 = car1 // Copy (value type)
car2.brand = "Honda"
print(car1.brand) // Toyota
print(car2.brand) // Honda
16. What is a lazy property in Swift?
A lazy property is a property whose value is not initialized until it is accessed for the first time.
Example:
class DataLoader {
lazy var data: String = loadData()
func loadData() -> String {
print("Loading data...")
return "Data Loaded"
}
}
let loader = DataLoader()
print("Before accessing data")
print(loader.data) // "Loading data..." will be printed only now
✅ Useful when initialization is expensive and unnecessary until accessed.
17. What is the difference between strong
, weak
, and unowned
references in Swift?
Type | Retains Object? | Prevents Memory Leak? | When to Use? |
---|---|---|---|
strong | ✅ Yes | ❌ No | Default, retains object strongly |
weak | ❌ No | ✅ Yes | Used for avoiding retain cycles (Optional) |
unowned | ❌ No | ✅ Yes | Similar to weak but non-optional |
Example (Weak Reference in Closures to Avoid Retain Cycle)
class Person {
var name: String
init(name: String) {
self.name = name
}
}
class Company {
var employee: Person?
}
var company: Company? = Company()
var person: Person? = Person(name: "Alice")
company?.employee = person
person = nil // Strong reference, leads to a memory leak
// To prevent this, use weak reference:
class SafeCompany {
weak var employee: Person?
}
18. What is a higher-order function in Swift?
A function that takes another function as a parameter or returns a function.
Example (map, filter, reduce):
let numbers = [1, 2, 3, 4, 5]
// Map: Squares each element
let squaredNumbers = numbers.map { $0 * $0 }
print(squaredNumbers) // Output: [1, 4, 9, 16, 25]
// Filter: Gets even numbers
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // Output: [2, 4]
// Reduce: Sums all elements
let sum = numbers.reduce(0, +)
print(sum) // Output: 15
19. What is the difference between escaping and non-escaping closures?
Closure Type | Description | Example Usage |
---|---|---|
Non-escaping (default ) | Closure is executed immediately within the function. | someFunction(closure: { print("Executed immediately") }) |
Escaping (@escaping ) | Closure is stored and executed later (e.g., async tasks). | completionHandler in networking calls. |
Example of @escaping closure:
func performTask(completion: @escaping () -> Void) {
DispatchQueue.global().async {
print("Task started")
completion() // Executes after async work
}
}
performTask {
print("Task completed")
}
20. What are protocols in Swift?
A protocol defines a blueprint of properties and methods that conforming types must implement.
Example:
protocol Vehicle {
var speed: Int { get set }
func move()
}
class Car: Vehicle {
var speed: Int = 0
func move() {
print("Car is moving at \(speed) km/h")
}
}
let car = Car()
car.speed = 60
car.move() // Output: Car is moving at 60 km/h
21. What is protocol extension in Swift?
Extensions allow adding default implementations to protocols.
Example:
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello!")
}
}
class Person: Greetable {}
let person = Person()
person.greet() // Output: Hello!
22. What is mutating keyword in Swift?
Used in structs to modify properties inside a method.
Example:
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
var counter = Counter()
counter.increment()
print(counter.count) // Output: 1
23. What is the difference between is
and as
in Swift?
Keyword | Purpose |
---|---|
is | Checks if an object belongs to a certain type |
as? | Attempts type casting (returns optional) |
as! | Forced type casting (crashes if it fails) |
Example:
let value: Any = "Hello"
if value is String {
print("It's a String")
}
if let str = value as? String {
print(str) // Output: Hello
}
24. How do you handle errors in Swift?
Using do-catch
with throw
statements.
Example:
enum FileError: Error {
case fileNotFound
}
func readFile(name: String) throws {
throw FileError.fileNotFound
}
do {
try readFile(name: "test.txt")
} catch {
print("Error: \(error)")
}
25. What is defer in Swift?
defer
ensures execution of cleanup code before the function exits.
Example:
func test() {
defer { print("Cleanup executed") }
print("Function running")
}
test()
// Output:
// Function running
// Cleanup executed
26. What is Generics in Swift?
Generics allow writing reusable functions and types.
Example:
func swapValues<T>(a: inout T, b: inout T) {
let temp = a
a = b
b = temp
}
var x = 10, y = 20
swapValues(a: &x, b: &y)
print(x, y) // Output: 20 10
27. What is the difference between Equatable
and Comparable
in Swift?
Protocol | Purpose |
---|---|
Equatable | Enables == and != comparisons |
Comparable | Enables < , > , <= , >= comparisons |
Example:
struct Person: Equatable, Comparable {
let name: String
let age: Int
static func < (lhs: Person, rhs: Person) -> Bool {
return lhs.age < rhs.age
}
}
let p1 = Person(name: "Alice", age: 25)
let p2 = Person(name: "Bob", age: 30)
print(p1 == p2) // Output: false
print(p1 < p2) // Output: true
28. What is property observer (willSet
and didSet
) in Swift?
Used to monitor changes in property values.
Example:
var count: Int = 0 {
willSet {
print("Will change to \(newValue)")
}
didSet {
print("Changed from \(oldValue) to \(count)")
}
}
count = 10
// Output:
// Will change to 10
// Changed from 0 to 10
29. What is a singleton in Swift?
A class that has only one instance throughout the application.
Example:
class Logger {
static let shared = Logger()
private init() {} // Prevents creating multiple instances
}
Logger.shared
Here are the next 15 Swift interview questions with detailed explanations and examples.
30. What is an enum in Swift?
An enum (enumeration) is a user-defined type that groups related values together.
Example:
enum Direction {
case north, south, east, west
}
var currentDirection = Direction.north
currentDirection = .south // Change value
Enums can also have associated values and raw values.
Example with Raw Values:
enum Status: Int {
case success = 200
case notFound = 404
}
print(Status.success.rawValue) // Output: 200
31. What is an associated value in enums?
Enums can store associated values, making them more dynamic.
Example:
enum Media {
case photo(String)
case video(Int, String)
}
let image = Media.photo("image.jpg")
let clip = Media.video(1080, "video.mp4")
32. What is a failable initializer in Swift?
A failable initializer (init?
) returns nil
if initialization fails.
Example:
struct User {
var age: Int
init?(age: Int) {
if age < 0 { return nil }
self.age = age
}
}
let user = User(age: -5) // Returns nil
33. What is a typealias in Swift?
A typealias renames an existing type for readability.
Example:
typealias Kilometers = Int
let distance: Kilometers = 100
34. What is a struct in Swift?
A struct (structure) is a value type that can hold properties and methods.
Example:
struct Car {
var brand: String
var speed: Int
}
var myCar = Car(brand: "Tesla", speed: 100)
35. What is a computed property?
A computed property does not store a value but computes it dynamically.
Example:
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 5, height: 10)
print(rect.area) // Output: 50
36. What is the difference between value types and reference types?
Feature | Value Type (Struct, Enum) | Reference Type (Class) |
---|---|---|
Memory | Stored in stack | Stored in heap |
Copy Behavior | Copies data | Shares reference |
Mutation | Immutable by default | Mutable |
Example:
struct StructExample {
var value = 10
}
var struct1 = StructExample()
var struct2 = struct1
struct2.value = 20
print(struct1.value) // Output: 10 (original unchanged)
print(struct2.value) // Output: 20 (new copy)
37. What is a delegate in Swift?
A delegate is a pattern where one object delegates responsibility to another.
Example:
protocol TaskDelegate {
func taskCompleted()
}
class Manager {
var delegate: TaskDelegate?
func completeTask() {
delegate?.taskCompleted()
}
}
class Employee: TaskDelegate {
func taskCompleted() {
print("Task done!")
}
}
let manager = Manager()
let employee = Employee()
manager.delegate = employee
manager.completeTask() // Output: Task done!
38. What is dynamic dispatch in Swift?
Dynamic dispatch allows method calls to be resolved at runtime instead of compile time.
Example:
class Parent {
func greet() {
print("Hello from Parent")
}
}
class Child: Parent {
override func greet() {
print("Hello from Child")
}
}
let obj: Parent = Child()
obj.greet() // Output: Hello from Child
39. What is an escaping closure?
An escaping closure is stored and executed later.
Example:
func performTask(completion: @escaping () -> Void) {
DispatchQueue.global().async {
completion()
}
}
performTask {
print("Task done!")
}
40. What is @objc in Swift?
@objc
allows Swift code to be used in Objective-C runtime.
Example:
import Foundation
class MyClass: NSObject {
@objc func greet() {
print("Hello")
}
}
41. What is NSCopying in Swift?
Used to create copies of objects.
Example:
class User: NSObject, NSCopying {
var name: String
init(name: String) {
self.name = name
}
func copy(with zone: NSZone? = nil) -> Any {
return User(name: self.name)
}
}
let user1 = User(name: "Alice")
let user2 = user1.copy() as! User
42. What is @discardableResult in Swift?
Used to suppress warnings when function return values are not used.
Example:
@discardableResult
func add(a: Int, b: Int) -> Int {
return a + b
}
add(a: 5, b: 3) // No warning even if result isn't used
43. What is the difference between static and class methods?
Modifier | Used In | Overridable? |
---|---|---|
static | Structs & Classes | ❌ No |
class | Only in Classes | ✅ Yes |
Example:
class Parent {
class func sayHello() {
print("Hello from Parent")
}
}
class Child: Parent {
override class func sayHello() {
print("Hello from Child")
}
}
Child.sayHello() // Output: Hello from Child
44. What is @available in Swift?
Marks functions or properties as available only for certain OS versions.
Example:
@available(iOS 15.0, *)
func newFeature() {
print("This is only available in iOS 15+")
}
45. What is @propertyWrapper in Swift?
It allows adding custom behavior to properties.
Example:
@propertyWrapper
struct Capitalized {
private var value: String = ""
var wrappedValue: String {
get { value }
set { value = newValue.capitalized }
}
}
struct User {
@Capitalized var name: String
}
var user = User()
user.name = "swift"
print(user.name) // Output: Swift
46. What is a Result
type in Swift?
Result<T, Error>
is an enum that represents success or failure.
Example:
enum NetworkError: Error {
case badURL
case noData
}
func fetchData(from url: String) -> Result<String, NetworkError> {
if url.isEmpty {
return .failure(.badURL)
}
return .success("Data received")
}
let result = fetchData(from: "")
switch result {
case .success(let data):
print(data)
case .failure(let error):
print("Error: \(error)")
}
47. What is @frozen
in Swift?
Marks an enum as frozen, preventing new cases from being added in future updates.
Example:
@frozen enum Status {
case success
case failure
}
✅ Improves performance by allowing compiler optimizations.
48. What is the difference between Any
and AnyObject
?
Type | Meaning |
---|---|
Any | Can hold any type, including structs, classes, and enums |
AnyObject | Can hold only class instances |
Example:
var anyValue: Any = 5
anyValue = "Hello" // Allowed
class Person {}
var object: AnyObject = Person() // Only class instances allowed
49. What is Codable
in Swift?
Codable
allows objects to be encoded/decoded into JSON.
Example:
struct User: Codable {
var name: String
var age: Int
}
let user = User(name: "Alice", age: 25)
let jsonData = try JSONEncoder().encode(user)
print(String(data: jsonData, encoding: .utf8)!) // JSON String
50. What is Decodable
vs Encodable
in Swift?
Protocol | Purpose |
---|---|
Encodable | Converts an object to JSON |
Decodable | Converts JSON to an object |
Codable | Combines both Encodable & Decodable |
51. What is KeyPath
in Swift?
A KeyPath is a way to refer to a property dynamically.
Example:
struct Person {
var name: String
}
let person = Person(name: "Alice")
let nameKeyPath = \Person.name
print(person[keyPath: nameKeyPath]) // Output: Alice
52. What is weak self
in Swift?
Used to avoid retain cycles in closures.
Example:
class Test {
var name = "Swift"
func execute() {
DispatchQueue.global().async { [weak self] in
print(self?.name ?? "No name")
}
}
}
53. What is the difference between private
and fileprivate
?
Access Level | Scope |
---|---|
private | Only inside the same class/struct |
fileprivate | Accessible in the same file |
Example:
class Test {
private var privateVar = "Private"
fileprivate var filePrivateVar = "Fileprivate"
}
54. What is some
keyword in Swift?
Used to define opaque return types that hide concrete type information.
Example:
func getNumber() -> some Numeric {
return 5
}
55. What is inout
in Swift?
Allows a function to modify arguments directly.
Example:
func swapValues(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
var x = 10, y = 20
swapValues(&x, &y)
print(x, y) // Output: 20 10
56. What is @testable
in Swift?
Allows unit tests to access internal properties and methods.
Example:
@testable import MyApp
57. What is defer
used for in Swift?
Executes cleanup code just before the function exits.
Example:
func test() {
defer { print("Cleanup") }
print("Function running")
}
test()
// Output:
// Function running
// Cleanup
58. What is guard
in Swift?
guard
is used to exit early if a condition fails.
Example:
func validate(name: String?) {
guard let name = name, !name.isEmpty else {
print("Invalid name")
return
}
print("Hello, \(name)")
}
59. What is NSCache
in Swift?
NSCache
stores objects temporarily in memory, automatically removing them when memory is low.
Example:
let cache = NSCache<NSString, NSString>()
cache.setObject("CachedValue", forKey: "key")
print(cache.object(forKey: "key")!) // Output: CachedValue
60. What is OperationQueue
in Swift?
A higher-level abstraction over GCD for handling concurrency.
Example:
let queue = OperationQueue()
queue.addOperation {
print("Task 1")
}
queue.addOperation {
print("Task 2")
}
61. What is didSet
and willSet
in Swift?
didSet
and willSet
are property observers that allow you to track changes to a property.
Example:
class Person {
var age: Int = 0 {
willSet(newAge) {
print("Age will change to \(newAge)")
}
didSet {
print("Age changed from \(oldValue) to \(age)")
}
}
}
var person = Person()
person.age = 25
// Output:
// Age will change to 25
// Age changed from 0 to 25
62. What is the difference between lazy var
and var
?
Feature | lazy var | var |
---|---|---|
Initialization | Only when accessed | When instance is created |
Storage | Heap memory | Stack memory |
Used in | Large computations, expensive setup | Regular variables |
Example:
class Example {
lazy var data = loadData()
func loadData() -> String {
print("Loading data...")
return "Data loaded"
}
}
let example = Example()
print("Before accessing data")
print(example.data) // "Loading data..." printed only now
63. What is the difference between throws
and rethrows
in Swift?
Feature | throws | rethrows |
---|---|---|
Used in | Functions that can throw errors | Functions that take a throwing closure and may rethrow the error |
Example:
func throwingFunction() throws {
throw NSError(domain: "Error", code: 1, userInfo: nil)
}
func rethrowingFunction(action: () throws -> Void) rethrows {
try action()
}
do {
try rethrowingFunction(action: throwingFunction)
} catch {
print("Error caught")
}
64. What is final
in Swift?
Prevents a class, method, or property from being overridden.
Example:
final class Animal {} // Cannot be subclassed
65. What is the difference between mutating
and non-mutating methods?
Feature | mutating | Non-mutating |
---|---|---|
Used in | Structs & Enums | Classes & Structs |
Modifies self ? | ✅ Yes | ❌ No |
Example:
struct Counter {
var count = 0
mutating func increment() {
count += 1
}
}
66. What is autoreleasepool
in Swift?
Used to manage memory in Objective-C style environments, mainly in iOS/macOS applications.
Example:
autoreleasepool {
let image = UIImage(named: "largeImage")
print("Loaded image")
}
67. What is assert
and precondition
in Swift?
Used for debugging and checking conditions at runtime.
Feature | assert | precondition |
---|---|---|
When used? | Debug mode | Both debug & release modes |
Effect | Stops execution if false | Stops execution if false |
Example:
let age = -3
assert(age >= 0, "Age cannot be negative") // Debug mode check
precondition(age >= 0, "Age cannot be negative") // Always checked
68. What is the difference between compactMap
and flatMap
?
Feature | compactMap | flatMap |
---|---|---|
Removes nil values? | ✅ Yes | ❌ No |
Flattens nested arrays? | ❌ No | ✅ Yes |
Example:
let numbers = ["1", "2", "a", "4"]
let validNumbers = numbers.compactMap { Int($0) } // [1, 2, 4]
let nestedArrays = [[1, 2], [3, 4]]
let flattenedArray = nestedArrays.flatMap { $0 } // [1, 2, 3, 4]
69. What is lazy var
with a closure?
Used to initialize a property lazily with a closure.
Example:
class Example {
lazy var message: String = {
return "Lazy property initialized"
}()
}
70. What is the difference between ==
and ===
in Swift?
Operator | Used for |
---|---|
== | Value equality (compares values) |
=== | Reference equality (compares memory addresses) |
Example:
class Person {}
let a = Person()
let b = a
print(a === b) // Output: true
71. What is type(of:)
in Swift?
Gets the runtime type of an object.
Example:
let name = "Swift"
print(type(of: name)) // Output: String
72. What is #keyPath
in Swift?
Refers to properties dynamically for KVO (Key-Value Observing).
Example:
class Car: NSObject {
@objc dynamic var speed = 0
}
let car = Car()
print(#keyPath(Car.speed)) // Output: "speed"
73. What is the difference between self
and Self
?
Feature | self | Self |
---|---|---|
Refers to | Current instance | Current type |
Example:
class Animal {
func printSelf() {
print(self) // Refers to instance
}
static func printSelfType() {
print(Self.self) // Refers to class type
}
}
74. What is the @UIApplicationMain
attribute?
Marks a class as the application entry point.
Example:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
75. What is @NSManaged
in Swift?
Used for Core Data properties that are dynamically resolved.
Example:
import CoreData
class Person: NSManagedObject {
@NSManaged var name: String
}
76. What is @objc
in Swift?
The @objc
attribute allows Swift methods, properties, and classes to be accessible in Objective-C.
Example:
import Foundation
class MyClass: NSObject {
@objc func sayHello() {
print("Hello from Objective-C compatible method")
}
}
77. What is @dynamicCallable
in Swift?
Allows instances of a class or struct to be called like functions.
Example:
@dynamicCallable
struct Callable {
func dynamicallyCall(withArguments args: [String]) {
print("Called with: \(args)")
}
}
let obj = Callable()
obj("Swift", "Dynamic", "Callable") // Output: Called with: ["Swift", "Dynamic", "Callable"]
78. What is @dynamicMemberLookup
in Swift?
Allows accessing unknown properties dynamically.
Example:
@dynamicMemberLookup
struct DynamicStruct {
subscript(dynamicMember member: String) -> String {
return "You accessed \(member)"
}
}
let obj = DynamicStruct()
print(obj.hello) // Output: You accessed hello
79. What is typealias
in Swift?
Defines an alternate name for an existing type.
Example:
typealias StringAlias = String
let message: StringAlias = "Hello"
80. What is the difference between static
and class
in Swift?
Keyword | Used for | Can be overridden? |
---|---|---|
static | Type-level properties/methods | ❌ No |
class | Type-level methods (only for classes) | ✅ Yes |
Example:
class Parent {
static func staticMethod() { print("Static method") }
class func classMethod() { print("Class method") }
}
class Child: Parent {
override class func classMethod() { print("Overridden class method") }
}
81. What is stride
in Swift?
Generates a sequence of values within a range.
Example:
for i in stride(from: 0, to: 10, by: 2) {
print(i) // Output: 0, 2, 4, 6, 8
}
82. What is first(where:)
in Swift?
Finds the first element matching a condition.
Example:
let numbers = [1, 2, 3, 4, 5]
if let num = numbers.first(where: { $0 > 2 }) {
print(num) // Output: 3
}
83. What is the difference between map
, filter
, and reduce
in Swift?
Method | Purpose |
---|---|
map | Transforms each element |
filter | Selects elements based on a condition |
reduce | Combines elements into a single value |
Example:
let numbers = [1, 2, 3, 4, 5]
let mapped = numbers.map { $0 * 2 } // [2, 4, 6, 8, 10]
let filtered = numbers.filter { $0 > 2 } // [3, 4, 5]
let reduced = numbers.reduce(0, +) // 15
84. What is merge
in Swift Dictionaries?
Merges two dictionaries.
Example:
var dict1 = ["A": 1, "B": 2]
let dict2 = ["B": 3, "C": 4]
dict1.merge(dict2) { (current, new) in new }
print(dict1) // Output: ["A": 1, "B": 3, "C": 4]
85. What is isMultiple(of:)
in Swift?
Checks if a number is a multiple of another number.
Example:
print(10.isMultiple(of: 2)) // Output: true
86. What is some
in Swift generics?
Defines opaque return types that hide the specific type.
Example:
func getNumber() -> some Numeric {
return 5
}
87. What is self
in escaping closures?
Using [weak self]
prevents retain cycles in closures.
Example:
class Test {
var name = "Swift"
func execute() {
DispatchQueue.global().async { [weak self] in
print(self?.name ?? "No name")
}
}
}
88. What is CaseIterable
in Swift?
Allows iteration over all cases of an enum.
Example:
enum Days: CaseIterable {
case Monday, Tuesday, Wednesday
}
for day in Days.allCases {
print(day)
}
89. What is isEmpty
for collections in Swift?
Checks if a collection is empty.
Example:
let arr: [Int] = []
print(arr.isEmpty) // Output: true
90. What is NotificationCenter
in Swift?
Used for inter-object communication.
Example:
NotificationCenter.default.addObserver(self, selector: #selector(handleNotification), name: Notification.Name("customEvent"), object: nil)
NotificationCenter.default.post(name: Notification.Name("customEvent"), object: nil)
Here are the final 10 Swift interview questions with detailed explanations and examples.
Top 100 Swift Interview Questions – Part 7
91. What is @discardableResult
in Swift?
Used to ignore a function’s return value without a warning.
Example:
@discardableResult
func increment(_ value: Int) -> Int {
return value + 1
}
increment(5) // No warning even if the result is unused
92. What is propertyWrapper
in Swift?
Encapsulates logic for property behavior.
Example:
@propertyWrapper
struct Uppercase {
private var text: String = ""
var wrappedValue: String {
get { text }
set { text = newValue.uppercased() }
}
}
struct User {
@Uppercase var name: String
}
var user = User()
user.name = "swift"
print(user.name) // Output: SWIFT
93. What is UUID
in Swift?
Generates unique identifiers.
Example:
let uniqueID = UUID().uuidString
print(uniqueID) // Example: "A1B2C3D4..."
94. What is weak
and unowned
in Swift?
Keyword | Used for | Becomes nil ? | Causes retain cycle? |
---|---|---|---|
weak | Optional references | ✅ Yes | ❌ No |
unowned | Non-optional references | ❌ No | ❌ No (but crashes if accessed after deallocation) |
Example:
class Owner {
var name: String
weak var pet: Pet?
init(name: String) {
self.name = name
}
}
class Pet {
var type: String
unowned var owner: Owner
init(type: String, owner: Owner) {
self.type = type
self.owner = owner
}
}
var person: Owner? = Owner(name: "John")
var dog: Pet? = Pet(type: "Dog", owner: person!)
person?.pet = dog
person = nil // `dog.owner` would crash if it were `unowned`
95. What is Codable
in Swift?
Encodes and decodes objects to and from JSON.
Example:
struct User: Codable {
var name: String
var age: Int
}
let user = User(name: "Alice", age: 25)
let jsonData = try JSONEncoder().encode(user)
print(String(data: jsonData, encoding: .utf8)!) // Output: {"name":"Alice","age":25}
96. What is defer
in Swift?
Executes code when exiting a scope.
Example:
func test() {
defer { print("Cleanup done!") }
print("Function started")
}
test()
// Output:
// Function started
// Cleanup done!
97. What is the difference between Any
and AnyObject
?
Type | Description |
---|---|
Any | Can hold any value, including structs, enums, and classes |
AnyObject | Can hold only class instances |
Example:
var anyValue: Any = 5
anyValue = "Swift"
var anyObject: AnyObject = NSString(string: "Hello")
// anyObject = 5 // Error: Not a class instance
98. What is the difference between guard
and if let
?
Feature | guard | if let |
---|---|---|
Used for | Early exit | Optional unwrapping |
Scope | Outside the block | Inside the block |
Improves readability? | ✅ Yes | ❌ No |
Example:
func checkName(_ name: String?) {
guard let name = name else {
print("Name is nil")
return
}
print("Hello, \(name)")
}
checkName(nil) // Output: Name is nil
99. What is Result
type in Swift?
Represents success and failure cases in functions.
Example:
enum NetworkError: Error {
case notFound
}
func fetchData() -> Result<String, NetworkError> {
return .success("Data loaded")
}
let result = fetchData()
switch result {
case .success(let data):
print(data)
case .failure(let error):
print("Error: \(error)")
}
100. What is Combine
framework in Swift?
Used for handling asynchronous and event-driven programming.
Example:
import Combine
let publisher = Just("Hello, Combine!")
let subscriber = publisher.sink { print($0) }
// Output: Hello, Combine!
Mastering Swift is crucial for a successful career in iOS app development. By reviewing these 100 Swift interview questions, you can strengthen your understanding of Swift fundamentals, object-oriented programming, memory management, closures, protocols, and more. Whether you’re applying for a role at a startup or a top tech company, practicing these questions will increase your confidence and improve your chances of success. Keep learning, stay updated with the latest Swift trends, and happy coding! 🚀