🍎 Swift & iOS Intermediate

What is the difference between nil coalescing and optional chaining?

Why Interviewers Ask This

This tests whether you can apply Swift & iOS knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

Both deal with optionals but serve different purposes: Optional chaining (?.): safely accesses properties or calls methods on an optional value. If the optional is nil, the entire chain returns nil (of the result type as Optional). Useful for navigating a chain of optional accesses: let user: User? = getUser() let count = user?.name?.count // Int? -- nil if user or name is nil let uppercased = user?.name?.uppercased() // String? // Calling methods: user?.save() // Nothing happens if user is nil // Setting through chain: user?.address?.city = "New York" // No-op if chain breaks. Nil coalescing (??): provides a default value when an optional is nil — always returns a non-optional: let name: String? = nil let displayName = name ?? "Anonymous" // "Anonymous" let count = user?.name?.count ?? 0 // 0 if anything in chain is nil // Chaining: let value = optional1 ?? optional2 ?? defaultValue. Combined: let streetName = user?.address?.street?.name ?? "No Street" // Chains ?.?.?. then provides default with ??. guard let vs if let vs ??: // if let -- use value in a scope: if let name = user?.name { print("Hello \(name)") } // guard let -- exit if nil: guard let name = user?.name else { return } print("Hello \(name)") // ?. -- chain without unwrapping: user?.name?.uppercased() // ?? -- need a non-optional fallback: user?.name ?? "Unknown". Use optional chaining when the nil case is acceptable; nil coalescing when you always need a concrete value.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Swift & iOS answers easy to follow.