Bird
Raised Fist0
Swiftprogramming~20 mins

Optional chaining with ?. in Swift - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Swift Optional Chaining Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this optional chaining example?
Consider the following Swift code. What will be printed when it runs?
Swift
class Person {
    var pet: Pet?
}

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

let person = Person()
if let petName = person.pet?.name {
    print(petName)
} else {
    print("No pet name")
}
AEmpty string
Bnil
CRuntime error
DNo pet name
Attempts:
2 left
💡 Hint
Think about what happens when you try to access a property of a nil optional using optional chaining.
❓ Predict Output
intermediate
2:00remaining
What does this optional chaining expression return?
Given the code below, what is the value of 'length' after execution?
Swift
class Book {
    var title: String?
}

let book = Book()
book.title = "Swift Guide"
let length = book.title?.count
print(length ?? "No length")
ANo length
B11
COptional(11)
Dnil
Attempts:
2 left
💡 Hint
Optional chaining returns an optional value even if the property is non-optional.
❓ Predict Output
advanced
2:00remaining
What is the output of this nested optional chaining?
Analyze the code and determine what will be printed.
Swift
class Engine {
    var horsepower: Int
    init(horsepower: Int) {
        self.horsepower = horsepower
    }
}

class Car {
    var engine: Engine?
}

let car = Car()
car.engine = Engine(horsepower: 150)

if let hp = car.engine?.horsepower {
    print("Horsepower: \(hp)")
} else {
    print("No engine horsepower")
}
ANo engine horsepower
BHorsepower: 150
Cnil
DRuntime error
Attempts:
2 left
💡 Hint
Check if the engine property is nil or not before accessing horsepower.
❓ Predict Output
advanced
2:00remaining
What error does this code produce?
What happens when you run this Swift code?
Swift
class House {
    var address: String
    init(address: String) {
        self.address = address
    }
}

var house: House?
house!.address = "123 Main St"
ARuntime error: Unexpectedly found nil while unwrapping an Optional value
BNo output, runs fine
CRuntime error: Index out of range
DCompile-time error: Use of unresolved identifier 'house'
Attempts:
2 left
💡 Hint
What happens if you force unwrap a nil optional?
🧠 Conceptual
expert
2:00remaining
How many items are in the resulting array after filtering with optional chaining?
Consider this Swift code snippet. How many elements does 'validLengths' contain after execution?
Swift
class Document {
    var text: String?
    init(text: String?) {
        self.text = text
    }
}

let docs = [Document(text: "Hello"), Document(text: nil), Document(text: "Swift"), Document(text: nil)]

let validLengths = docs.compactMap { $0.text?.count }
A2
B4
C0
D3
Attempts:
2 left
💡 Hint
compactMap removes nil values after optional chaining.

Practice

(1/5)
1. What does the ?. operator do in Swift when used with optionals?
easy
A. It forces unwraps the optional and crashes if nil.
B. It converts the optional to a non-optional value automatically.
C. It safely accesses a property or method and returns nil if the optional is nil.
D. It assigns a default value if the optional is nil.

Solution

  1. Step 1: Understand optional chaining purpose

    The ?. operator is used to safely access properties or methods on an optional value.
  2. Step 2: Behavior when optional is nil

    If the optional is nil, the chaining stops and returns nil instead of crashing.
  3. Final Answer:

    It safely accesses a property or method and returns nil if the optional is nil. -> Option C
  4. Quick Check:

    Optional chaining = safe access with nil return [OK]
Hint: Remember: ? stops if nil, no crash happens [OK]
Common Mistakes:
  • Confusing optional chaining with forced unwrapping
  • Thinking it unwraps optionals automatically
  • Assuming it provides default values
2. Which of the following is the correct syntax to safely access the name property of an optional person object using optional chaining?
easy
A. person->name
B. person!.name
C. person.name?
D. person?.name

Solution

  1. Step 1: Identify correct optional chaining syntax

    Optional chaining uses ?. between the optional variable and the property.
  2. Step 2: Check each option

    person?.name uses person?.name, which is correct syntax. person!.name forces unwraps with !. person.name? places ? incorrectly. person->name uses invalid operator.
  3. Final Answer:

    person?.name -> Option D
  4. Quick Check:

    Optional chaining syntax = variable?.property [OK]
Hint: Use ?. right before the property to chain safely [OK]
Common Mistakes:
  • Using ! instead of ? for optional chaining
  • Placing ? after the property name
  • Using invalid operators like ->
3. Consider the following Swift code:
class Person {
  var pet: Pet?
}
class Pet {
  var name: String
  init(name: String) { self.name = name }
}

let person = Person()
let petName = person.pet?.name
print(petName)

What will be printed?
medium
A. Optional(nil)
B. nil
C. An empty string
D. Runtime error

Solution

  1. Step 1: Analyze the optional chaining result

    Since person.pet is nil (not assigned), person.pet?.name returns nil of type String?.
  2. Step 2: Understand print output of optional nil

    Printing an optional value that is nil in Swift shows Optional(nil) because the variable itself is an optional.
  3. Final Answer:

    Optional(nil) -> Option A
  4. Quick Check:

    print(String? nil) = Optional(nil) [OK]
Hint: Printing optional nil shows 'Optional(nil)', not 'nil' [OK]
Common Mistakes:
  • Thinking print shows nil
  • Expecting empty string output
  • Thinking it causes runtime error
4. The following Swift code causes a compile error. What is the mistake?
struct Car {
  var owner: Person?
}

let car = Car()
let ownerName = car.owner?.name!
medium
A. Using forced unwrap (!) after optional chaining without parentheses
B. Missing initialization of car variable
C. Incorrect use of optional chaining operator
D. Person type does not have a name property

Solution

  1. Step 1: Identify forced unwrap misuse

    The code uses car.owner?.name! which tries to force unwrap the property without parentheses.
  2. Step 2: Correct syntax for forced unwrap after optional chaining

    Forced unwrap must be applied to the entire optional chaining expression with parentheses like (car.owner?.name)!.
  3. Final Answer:

    Using forced unwrap (!) after optional chaining without parentheses -> Option A
  4. Quick Check:

    Force unwrap after optional chaining needs parentheses [OK]
Hint: Wrap optional chain in () before ! to force unwrap [OK]
Common Mistakes:
  • Forgetting parentheses around optional chain before !
  • Assuming optional chaining can be forced unwrapped directly
  • Ignoring compiler error details
5. Given the following classes:
class Address {
  var city: String?
}
class User {
  var address: Address?
}

let user = User()

Which code safely prints the city name if it exists, or "Unknown" if city or address is nil?
hard
A. print(user.address.city ?? "Unknown")
B. print(user.address?.city ?? "Unknown")
C. print(user.address!.city!)
D. print(user.address?.city!)

Solution

  1. Step 1: Understand optional chaining with nil coalescing

    Using user.address?.city safely accesses city, returning nil if address or city is nil.
  2. Step 2: Use nil coalescing operator to provide default

    The ?? "Unknown" provides "Unknown" if the optional is nil, avoiding crashes.
  3. Final Answer:

    print(user.address?.city ?? "Unknown") -> Option B
  4. Quick Check:

    Optional chaining + ?? = safe access with default [OK]
Hint: Combine ?. with ?? to provide default value safely [OK]
Common Mistakes:
  • Forcing unwraps causing runtime crashes
  • Not handling nil for nested optionals
  • Using optional chaining without default fallback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard