SWIFT / CHAPTER 04

Functions and optional results

Intermediate

Represent missing values without unsafe assumptions.

By the end of this chapter

  • Read optional result types
  • Unwrap safely with if let
  • Use a meaningful nil fallback

The idea

An optional such as Int? contains either a value or nil. It describes absence in the type rather than encoding it as an ordinary number that could be valid data. Converting text with Int(...) returns an optional because the text might not be a valid integer. A function signature should make that possibility visible to its callers.

Optional binding with if let or guard let introduces a usable nonoptional value only in the successful path. The nil-coalescing operator ?? supplies a fallback when no value is present. Forced unwrapping with ! should not be a substitute for understanding the input. When failure is expected, choose an explicit branch that can explain or recover from it.

Swift example
func nextCount(_ text: String) -> Int? {
    guard let value = Int(text) else { return nil }
    return value + 1
}
print(nextCount("8") ?? -1)
print(nextCount("eight") ?? -1)
Result
9
-1

Valid numeric text is unwrapped and incremented. Invalid text returns nil, so the caller chooses its explicit fallback.

Try it yourself

Write a function returning an optional nonnegative integer from text and rejecting negative values.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
let value: Int? = 0
print(value ?? 7)