Here are 100 Swift interview questions and answers, focusing entirely on the Swift language—covering syntax, data types, control flow, object-oriented programming, protocols, closures, memory management, concurrency, and advanced features.
Swift Language Fundamentals
1. What is Swift?
Swift is a powerful, general-purpose, compiled programming language developed by Apple for iOS, macOS, watchOS, tvOS, and beyond. It combines modern language features like type safety, closures, protocol-oriented programming, and automatic memory management (ARC).
2. What is the difference between let and var?let declares a constant (cannot be changed after initialization). var declares a variable (mutable).
3. What are optionals, and how do you safely handle them?
An optional represents a value that may or may not exist. Safe unwrapping methods are if let, guard let, nil‑coalescing operator (??), optional chaining (?.), and force unwrapping (!) only when you are absolutely certain the value exists.
4. Explain type inference in Swift.
Swift can automatically deduce the type of a variable or constant based on the value assigned during initialization. For example, let name = "John" infers name as String.
5. What are tuples?
A tuple groups multiple values into a single compound value. They can be of any type and do not have to be named. Example: let person = (name: "Alice", age: 30).
6. What is the difference between nil in Swift and null in other languages?
In Swift, nil is the absence of a value for any optional type—it is not a pointer to a non‑existent object. It can be used with both reference and value types (via optionals).
7. What is type aliasing?typealias creates an alternative name for an existing type, making code more expressive. Example: typealias AudioSample = UInt16.
8. What are range operators? Give examples.
Closed range 1...5 (includes 5), half‑open range 1..<5 (excludes 5). There is also one‑sided ranges 2... and ...5.
9. What is the is and as operators?is checks whether an instance is of a certain subclass type. as is used for type casting (upcast as, downcast as? and as!).
10. How do you write comments in Swift?
Single‑line //, multi‑line /* */, and nestable multi‑line. Also, Swift supports markup comments (/// and /** */) for documentation.
Data Types & Collections
11. What are the basic value types in Swift?Int, Double, Float, Bool, String, Character, Array, Dictionary, Set, Enum, Struct, Tuple, and Optional.
12. What is the difference between Double and Float?Double has 64‑bit precision, Float has 32‑bit; Double is the default for floating‑point numbers.
13. Are arrays in Swift mutable?
Arrays declared with var are mutable (can append, remove). Arrays declared with let are immutable.
14. How do you create an empty array or dictionary?var array = [Int]() or var dict = [String: Int](). You can also use Array<Int>() or Dictionary<String, Int>().
15. What is the difference between Array and Set?Array is an ordered collection with duplicates allowed; Set is an unordered collection of unique elements. Sets have faster lookup for membership.
16. What is a dictionary in Swift?
A collection of key‑value pairs. Keys must be hashable and unique. Created with [KeyType: ValueType]().
17. Explain the for-in loop.for item in collection { … } iterates over every item in a sequence. You can also iterate over ranges.
18. How do you iterate over a dictionary?for (key, value) in dictionary { … } or simply for (_, value) in dictionary if you need only values.
19. What is the switch statement in Swift?
A control flow construct that matches values against patterns. No implicit fallthrough; each case must have at least one executable statement. You can use fallthrough explicitly.
20. What is pattern matching in switch?
Matching against value ranges (case 0..<10:), tuples, type casting, where clauses, and enums with associated values.
Control Flow
21. What is the guard statement and how is it used?
An early‑exit statement. If the condition is false, the else block must transfer control (return, throw, break, continue). Unwrapped optional values remain available in the outer scope.
22. What is the difference between if let and guard let?if let unwraps an optional for use inside its block. guard let unwraps and exits early if nil, keeping the unwrapped value alive in the enclosing function.
23. What is a defer statement?
Schedules a block to be executed when the current scope is exited, regardless of how it exits. Useful for cleanup, like closing files.
24. How does the where clause work in loops?for item in array where condition filters items before executing the loop body.
25. What is fallthrough in switch?
Explicitly continues execution to the next case without checking its pattern. By default, Swift does not fall through.
26. Explain while vs repeat-while.while evaluates the condition before the first iteration. repeat-while (similar to do-while) guarantees the block runs at least once.
27. Can you omit the Braces in if statements?
No. Swift requires braces even for single‑line bodies.
28. What are labeled statements?
You can label loops or if statements to use with break or continue to control which loop is broken: outerLoop: for …
29. How do you use break in a switch?
Normally switch cases end immediately after executing. break can be used to explicitly exit a case or to satisfy the requirement that every case must have an executable statement.
30. What is a for-where loop?for item in items where condition filters out elements that don’t satisfy the condition, skipping them without nested if.
Functions & Closures
31. How do you define a function in Swift?func functionName(param: Type) -> ReturnType { … }. Parameters can have external and internal names.
32. What is the purpose of argument labels?
They make function calls more readable. By default, parameters use both an external label (same as parameter name) and an internal name. You can omit the external label with _.
33. Explain variadic parameters.
A parameter that accepts zero or more values of a specified type: func sum(_ numbers: Int...) -> Int. Accessible as an array inside the function.
34. What are in‑out parameters?inout allows a function to modify a variable passed to it. Prefix with & when calling. Passed by reference for the duration of the call.
35. What is a function type?
Each function has a type composed of its parameter types and return type. Example: (Int, Int) -> Bool. Can be used as variables or parameters.
36. What are closures?
Self‑contained blocks of functionality that can be passed around. They capture and store references to constants and variables from their context.
37. What is a trailing closure?
If the last argument of a function is a closure, you can write it outside the parentheses. Example: array.sort { $0 < $1 }.
38. What is the difference between escaping and non‑escaping closures?
Non‑escaping (default) closures must complete within the function’s scope. Escaping closures (marked @escaping) are allowed to outlive the function call (e.g., stored for async completion).
39. How do you avoid strong reference cycles with closures?
Use a capture list: { [weak self] in … } or { [unowned self] in … } to prevent the closure from holding a strong reference to self.
40. What is autoclosure?
A closure that is automatically created to wrap an expression passed as a function argument. Annotated with @autoclosure. Delays evaluation.
41. What is map, filter, reduce?
Higher‑order functions: map transforms each element, filter selects elements meeting a condition, reduce combines elements into a single value.
Classes & Structs
42. What is the difference between a class and a struct?
Classes are reference types (shared), support inheritance, deinitializers, and type casting. Structs are value types (copied), cannot inherit, have memberwise initializers automatically, and are generally preferred unless identity or inheritance is needed.
43. What does it mean that structs are value types?
When you assign a struct to a new variable or pass it as an argument, a copy is made. Modifying the copy does not affect the original.
44. What is identity and equality (=== vs ==)?== checks value equality. === checks identity (two references point to the exact same instance). Applies only to class instances.
45. How do you define a class initializer?init(parameters) { … }. All stored properties must be initialized before the instance can be used.
46. What is a designated initializer vs. convenience initializer?
Designated initializers fully initialize all properties and call superclass initializer. Convenience initializers call designated initializers within the same class and are marked convenience.
47. What is a failable initializer?init?() that may return nil if initialization fails. Can be used to gracefully handle invalid parameters.
48. Explain inheritance in Swift.
A class can inherit methods, properties, and other characteristics from another class. Mark the base class methods as open or public to allow overriding. Swift does not support multiple inheritance of classes, only protocols.
49. What is the final keyword?
Prevents a method, property, or class from being overridden or subclassed. Indicates performance benefits by avoiding dynamic dispatch.
50. What are required initializers?required init must be implemented by every subclass.
51. How do you override a property?
Using the override keyword. You can provide a custom getter and/or setter, or add property observers in the override.
52. What is didSet and willSet?
Property observers: willSet is called just before a value is stored, didSet immediately after. They are not called during initialization.
53. What are lazy stored properties?
A property whose initial value is not calculated until the first time it is used. Declared with lazy var. Not thread‑safe.
54. What are computed properties?
Properties that do not actually store a value; they provide a getter and an optional setter. Must be declared var.
55. What are type properties (static / class)?
Belong to the type itself, not an instance. static for all types; class allows override in subclasses (classes only).
Enumerations
56. How are enums defined in Swift?enum CompassPoint { case north, south, east, west }. Can contain associated values and raw values.
57. What are associated values?
Each enum case can store additional custom values of any type, defined alongside the case. Example: enum Barcode { case upc(Int, Int, Int, Int); case qrCode(String) }.
58. What are raw values?
Pre‑populated default values of the same type for every case. Example: enum Planet: Int { case mercury = 1, venus, earth }. Access with .rawValue.
59. Can enums have methods?
Yes, enums can have methods, computed properties, and conform to protocols.
60. What is indirect enums?
Marked with indirect, a case’s associated value can be another instance of the same enum, enabling recursive data structures (e.g., tree).
Protocols
61. What is a protocol?
A blueprint of methods, properties, and other requirements that suit a particular task. Any type can conform to a protocol.
62. What is protocol conformance?
A class, struct, or enum that supplies the actual implementation of the required methods and properties.
63. What is a protocol extension?
Adds method and property implementations to a protocol, enabling default behavior for all conforming types.
64. What is a protocol composition?
Combining multiple protocols into a single requirement using &, e.g., func foo(item: Codable & Equatable).
65. What are Any and AnyObject?Any can represent an instance of any type at all, including function types and optional types. AnyObject can represent an instance of any class type.
66. What is the Equatable protocol?
Conforming types can be compared using == and !=. The compiler can auto‑synthesize for structs with all‑equatable properties and enums.
67. What is Hashable?
Conforming types provide a hash value (via hash(into:)). Required for use as dictionary keys or in sets. Auto‑synthesized for eligible types.
68. What is Codable?
A combination of Encodable and Decodable. Allows types to be converted to and from external representations like JSON or property lists.
69. What are protocol‑oriented programming principles?
Favoring composition with protocols and protocol extensions over class inheritance, enabling default implementations and mixing behaviors from multiple protocols.
70. What is associatedtype?
A placeholder name used in a protocol for a type that is used as part of the protocol. The actual type is not specified until the protocol is adopted.
Generics
71. What are generics?
Generics enable writing flexible, reusable functions and types that can work with any type, subject to requirements. Example: func swap<T>(a: inout T, b: inout T).
72. What is a generic type constraint?
Specify that a type parameter must inherit from a specific class, or conform to a particular protocol or protocol composition: <T: Equatable>.
73. What is the where clause in generics?
Adds additional requirements on type parameters or associated types. Example: func allItemsMatch<C1: Container, C2: Container>(…) where C1.Item == C2.Item, C1.Item: Equatable.
74. What is an opaque type?some Protocol hides the concrete return type, exposing only the protocol interface. Used extensively in SwiftUI.
75. What is the difference between AnyView and some View?some View is a compiler‑known opaque type; AnyView is a type‑erased wrapper. some View is preferred for performance and static type guarantees.
Error Handling
76. How do you handle errors in Swift?
Functions marked throws can throw errors. Errors are caught using do { try function() } catch { }.
77. What is try? and try!?try? returns an optional (nil on error). try! forces a call and will crash if an error is thrown. Use sparingly.
78. How do you define a custom error type?
By creating an enum that conforms to the Error protocol, or a struct. Enum cases can hold associated values.
79. What is rethrows?
A function that takes a throwing closure parameter and only throws if that closure throws; doesn’t throw on its own.
80. What is defer in error‑prone code?
Cleanup actions that run no matter if a function throws or returns normally, but they do not execute if the program crashes.
Memory Management
81. How does Automatic Reference Counting (ARC) work?
Every time a class instance is assigned to a variable or constant, ARC increments its reference count. When the count drops to zero, the instance is deallocated.
82. What is a strong reference cycle?
Two class instances hold strong references to each other, preventing both from ever being deallocated.
83. How do you break a strong reference cycle?
Using weak or unowned references. weak becomes nil when the instance is deallocated; unowned assumes it never becomes nil.
84. What is a capture list in a closure and why is it used?[weak self] or [unowned self] in closures avoids capturing self strongly, preventing retain cycles.
85. What is an unowned optional reference?
An unowned reference combined with Optional (introduced in Swift 5.0) that does not retain the object, but is allowed to become nil after the object is deallocated, crashing on access if already nil.
Concurrency (Swift 5.5+)
86. What is async/await?
Structured concurrency: async marks a function that can be suspended; await waits for an asynchronous result without blocking the thread. It writes asynchronous code sequentially.
87. What is Task?
A unit of asynchronous work. You can create a Task and run async code inside it. Supports cancellation, priority, and task groups.
88. What is an actor?
A reference type that protects its mutable state by ensuring only one task accesses its data at a time, eliminating data races.
89. How do you call an async function from a non‑async context?
Wrap it in a Task { await asyncFunc() }. This creates an unstructured task.
90. What is MainActor?
A global actor that ensures code runs on the main thread. Add @MainActor to functions, properties, or classes.
91. What is withUnsafeCurrentTask?
Used for advanced task introspection; generally not needed in daily work.
92. What is async let?
Allows you to start multiple async operations concurrently and await their results later, while still within a structured concurrency context.
Advanced & Miscellaneous
93. What is a Result Builder?
A language feature used to build declarative DSLs (like SwiftUI views). Mark a type with @resultBuilder and define buildBlock and other static methods.
94. What are property wrappers?
A layer of separation between code that manages how a property is stored and the code that defines the property. Example: @State, @Published, @UserDefaults.
95. What is @frozen enum?
An enum that guarantees no new cases will be added in future library versions, enabling exhaustive switches without a default for future compatibility.
96. How does Mirror work?Mirror(reflecting:) provides a representation of the structure and values of any type, useful for debugging or serialization.
97. What is ExpressibleBy... protocols?
Literal expression protocols (ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, etc.) allow custom types to be initialized with literal syntax.
98. What is NSObject and when would you use it in Swift?
The root class of most Objective‑C class hierarchies. You rarely subclass it in pure Swift unless interfacing with KVO or certain UIKit/AppKit APIs that require it.
99. What is key path (\.) ?
Key paths provide a type‑safe way to refer to a property of a type. Used for KVO, dynamic member lookup, and SwiftUI bindings.
100. How do you stay up to date with Swift evolution?
Follow the Swift Evolution GitHub repository, swift.org blog, Swift Forums, and WWDC sessions. Actively test proposals in the snapshots.
Conclusion
You’ve done it — every question reviewed, every answer internalized, and now your excitement is absolutely contagious!
You’re not just walking into that interview; you’re practically bouncing in, buzzing with enthusiastic energy that says, “Ask me anything about Swift!” Whether it’s optionals, protocols, generics, ARC, or the magic of SwiftUI, your brain is now a treasure chest of crisp, ready-to-share knowledge, and you can’t wait to open it.
That genuine enthusiasm you’re feeling right now is your superpower. Interviewers can spot passion from a mile away, and yours will fill the room the moment you start talking about your love for clean code, elegant architecture, and the Apple ecosystem. You’ve moved past nervousness into pure, joyful readiness.
So go chase that opportunity with all the enthusiasm in your heart. Smile wide, answer with fire, and leave no doubt that you’re the kind of Swift developer they’d be crazy not to hire. This is your moment — now go own it!