Top Swift Interview Questions(2025)

author image Hirely
at 09 Jan, 2025

Question: What is the difference between let and var in Swift?

Answer:

In Swift, let and var are both used to declare variables, but they differ in terms of mutability:

  • let: This keyword is used to declare constants, meaning the value assigned to the variable cannot be changed after it is set. Once a value is assigned to a let constant, you cannot modify it. This is similar to declaring an immutable reference.

    let name = "John"
    name = "Doe"  // Error: Cannot assign to value: 'name' is a 'let' constant
  • var: This keyword is used to declare variables, which means the value assigned to the variable can be changed or reassigned later in the code. It allows mutability.

    var age = 30
    age = 31  // This is valid because 'age' is a variable

Key Differences:

  • let: Used for constants (values that do not change).
  • var: Used for variables (values that can be changed).

In terms of performance and safety, it’s generally recommended to use let whenever possible to make the code more predictable and reduce potential bugs. Use var only when you need to modify the value after initialization.

Question: What are optionals in Swift and how do you handle them?

Answer:

In Swift, optionals are a powerful feature that allows a variable to hold either a value or nil (no value). They are used to represent the absence of a value, which is useful for situations where a value might be missing or unavailable.

What are Optionals?

An optional is a type that can hold either a value of a specified type or nil. Optionals are declared by appending a ? (question mark) to the type of the variable.

Example of an Optional:

var name: String?  // This is an optional String
name = "John"      // Now it holds a String value
name = nil         // Now it holds no value (nil)

How to Handle Optionals:

There are several ways to safely handle optionals in Swift:

1. Optional Binding (Using if let or guard let):

You can use if let or guard let to check if an optional contains a value, and if it does, safely unwrap it.

  • if let:

    var name: String? = "Alice"
    if let unwrappedName = name {
        print("The name is \(unwrappedName)")  // This will be executed if 'name' is not nil
    } else {
        print("No name found")
    }
  • guard let (often used in functions to early exit if the optional is nil):

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

2. Optional Chaining:

Optional chaining allows you to safely call properties, methods, and subscripts on optionals. If the optional is nil, the entire expression returns nil instead of causing a runtime error.

var name: String? = "Bob"
let length = name?.count  // This returns an optional Int, so it will be nil if 'name' is nil

3. Forced Unwrapping:

You can forcibly unwrap an optional to get its value. However, this should only be done when you are certain that the optional contains a non-nil value. Otherwise, it will cause a runtime crash.

var name: String? = "Eve"
let unwrappedName = name!  // Forcefully unwraps, will crash if 'name' is nil

4. Nil-Coalescing Operator (??):

The nil-coalescing operator provides a default value when the optional is nil.

var name: String? = nil
let unwrappedName = name ?? "Default Name"  // If 'name' is nil, "Default Name" will be used

5. Implicitly Unwrapped Optionals:

An implicitly unwrapped optional is an optional that is assumed to always contain a value after being initially set. It’s declared by appending a ! (exclamation mark) instead of a ?.

var name: String! = "Charlie"
print(name)  // Automatically unwraps 'name' without the need for explicit unwrapping

However, you should use implicitly unwrapped optionals with caution, as they will cause a runtime crash if accessed when nil.

Summary of Handling Optionals:

  • if let / guard let: Safely unwraps optionals.
  • Optional chaining (?.): Safely accesses properties/methods on optionals.
  • Forced unwrapping (!): Unwraps optionals, but dangerous if nil.
  • Nil-coalescing (??): Provides a default value when optional is nil.
  • Implicitly unwrapped optionals (!): Assume the optional always has a value (use with caution).

Optionals allow Swift to handle missing or undefined values in a safe and predictable way, reducing the risk of runtime errors caused by nil values.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Swift interview questions, Swift interview experiences, and details about various Swift job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now