Swift Interview Questions

1. What is Swift?

Swift is a powerful, intuitive, and type-safe programming language developed by Apple for building apps across all Apple platforms, including iOS, macOS, watchOS, and tvOS. It's:

  • Fast – Swift uses LLVM to compile to optimized native code.
  • Safe – Swift eliminates entire classes of unsafe code, like null pointer dereferencing.
  • Modern – With features like optionals, type inference, closures, generics, and protocol-oriented programming.
  • Open-source – Swift is open-source and has a growing community.

Swift encourages best practices like immutability, value semantics, and strict type checking, making it easier to write clean, reliable, and maintainable code.

2. What are Optionals in Swift?

An Optional is a type that can either hold a value or no value (nil). It helps avoid crashes by explicitly handling missing or unexpected values.

var name: String? = "Alice" 
Name = nil // This is valid 

To use an optional, you need to unwrap it safely:

Optional binding:

if let actualName = name {     
     print(actualName) 
} 

Optional chaining:

print(name?.count)

Optionals improve safety by forcing the developer to deal with cases where a value might be absent.

3. What is the difference between var and let?

KeywordMeaningExample
varMutable (value can change)var age = 25
letImmutable (constant)let name = "John"
var age = 25 
age = 26 // OK  

let name = "John" 
// name = "Mike" // Error: Cannot reassign a constant 

Using let wherever possible makes your code safer and easier to reason about.

4. What is a Tuple?

A tuple is a group of multiple values bundled into one compound value. Useful for returning multiple values from a function.

let user = (name: "Alice", age: 25) 
Print(user.name) // Alice 

You can also destructure:

let (username, userAge) = user

5. What is guard in Swift?

guard is used for early exits when conditions aren’t met. It's commonly used for input validation and optional unwrapping.

func greet(user: String?) {     
      guard let name = user else {         
            print("No user provided")        
            return    
       }   
     print("Hello, \(name)")
 } 

Advantages:

  • Cleaner, flatter code
  • Forces you to handle failure early

6. Difference between Class and Struct?

FeatureClassStruct
TypeReferenceValue
InheritanceYesNo
ARC (memory mgmt)YesNo
MutabilityRequires var declarationMutability depends on usage
Copy BehaviorShared (reference)Independent copy (value)

Use structs for simple data models, and classes when identity, inheritance, or shared reference is needed.

7. What is a Protocol?

A protocol is a blueprint of methods and properties that a conforming type must implement.

protocol Greetable {     
          func greet() 
}  

class Person: Greetable {     
          func greet() {         
              print("Hi there!")    
             }
} 

Protocols enable polymorphism, decoupling, and are a core part of protocol-oriented programming, which Swift emphasizes.

8. What is Type Inference?

Swift can infer types based on initial values, reducing boilerplate code:

let name = "Apple" // Inferred as String
Let age = 10       // Inferred as Int 

You can still explicitly define types when clarity or precision is needed.

9. What is Optional Binding?

A safe way to unwrap optionals and access the underlying value:

if let name = optionalName {     
      print("Hello, \(name)") 
} 

You can also use guard let or if var to unwrap and mutate.

10. What is ?? (Nil-Coalescing Operator)?

Provides a default fallback value if the optional is nil:

let name = optionalName ?? "Guest"

This is a concise way to handle missing values gracefully.

11. What are Closures in Swift?

A closure is a self-contained block of code that can be passed and stored.

let greet = {     
    print("Hello!") 
} 
Greet() 

With parameters:

let add = { (a: Int, b: Int) -> Int in     
      return a + b 
} 

Closures capture values from their surrounding context. They are used in callbacks, functional operations, and asynchronous tasks.

12. What is an Enum?

An enum defines a group of related values and makes your code more readable and type-safe.

enum Direction {    
        case north, south, east, west 
} 
Let dir = Direction.north 

13. What is defer in Swift?

defer executes code just before the function exits. Useful for cleanup tasks like closing a file or stopping a spinner.

func loadFile() {     
        print("Opening file")     
        defer {         
                    print("Closing file")     
        }     
      print("Reading file") 
} 

14. What is the difference between weak and unowned?

  • weak: Optional reference that becomes nil when the object is deallocated.
  • unowned: Non-optional reference that assumes the object always exists (will crash if nil).

Use weak for delegates and avoid retain cycles in closures.

15. What is ARC (Automatic Reference Counting)?

Swift uses ARC to manage memory. It tracks how many references point to an object and deallocates it when no one is using it.

class Person {     
       var name: String     
       init(name: String) { self.name = name } 
} 

16. What is optional chaining?

Allows safe access to properties/methods of an optional without unwrapping it manually.

let count = user?.contacts?.count

If user or contacts is nil, the whole expression returns nil.

17. What is a computed property?

A property that doesn't store a value but calculates it each time it's accessed.

struct Person {     
        var firstName: String     
        var lastName: String     
        var fullName: String {         
                return "\(firstName) \(lastName)"     
          } 
} 

18. What is a lazy property?

A property whose initial value is not calculated until the first time it's used. Must be declared with var.

lazy var data = loadData()

19. What are higher-order functions in Swift?

Functions that take other functions as parameters or return functions. Common ones include:

  • map: transforms values
  • filter: filters elements
  • reduce: combines values into one
let numbers = [1, 2, 3]
Let doubled = numbers.map { $0 * 2 } // [2, 4, 6] 

20. What does @escaping mean in Swift?

Used to indicate a closure will outlive the function it's passed into — often in async operations like network requests.

func fetchData(completion: @escaping () -> Void) {     
           DispatchQueue.global().async {         
                  // Simulate delay         
                  completion()     
             } 
}