skip to content

Built-in Value Types

Numbers, booleans, tuples, strings and Optional: the types every line uses. Interviewers probe the places Swift is stricter than other languages: conversion, text indexing and absence.

on this pageshow

explore

questions

16

In Swift, how do you unwrap an Optional with if let and guard let, and when is each the better fit?

level: juniorimportance: must knowfreq 85%

answer

  1. where the bound name lives
  2. guard's else must leave the scope
  3. Swift 5.7 shorthand
  4. shorthand takes a plain identifier

basics

~20 s

if let binds the wrapped value only inside its own braces; guard let binds it for the rest of the enclosing scope and its else branch must exit. Since Swift 5.7, if let name unwraps an existing variable of the same name.

solid answer

~50 s

Both are *optional binding*: the condition succeeds only when the `Optional` holds a value, and the new constant has the non-optional type. `if let middleName = profile.middleName { … }` scopes `middleName` to the braces, so it suits a value you need briefly or an extra step that only happens when the value exists. `guard let profile else { return "?" }` keeps the unwrapped `profile` for the rest of the function, and the compiler rejects an `else` block that can fall through, so it suits preconditions at the top of a function. Since Swift 5.7 (SE-0345), `if let name` and `guard let name` unwrap a variable into a shadow with the same name; the shorthand accepts only a plain identifier, so `if let profile.middleName` is an error. Several bindings and Boolean tests can share one condition list, separated by commas.

code

swift · 26 lines
swift
struct UserProfile {
    let firstName: String
    let middleName: String?
    let lastName: String
}

func displayName(for profile: UserProfile) -> String {
    let middleName = profile.middleName
    if let middleName {
        return "\(profile.firstName) \(middleName) \(profile.lastName)"
    }
    return "\(profile.firstName) \(profile.lastName)"
}

func initials(for profile: UserProfile?) -> String {
    guard let profile else {
        return "?"
    }
    // profile is a non-optional UserProfile from here to the end of the function
    return String(profile.firstName.prefix(1)) + String(profile.lastName.prefix(1))
}

let ana = UserProfile(firstName: "Ana", middleName: nil, lastName: "Silva")
print(displayName(for: ana))   // Ana Silva
print(initials(for: ana))      // AS
print(initials(for: nil))      // ?

go deeper

for a junior

Recall the two shapes: if let gives you the value inside its braces, guard let gives you the value after the guard and forces the else branch to exit.

for a middle

Explain scope and the fall-through rule, show the Swift 5.7 shorthand and its plain-identifier limit, and combine bindings and Boolean tests in one condition list.

for a senior

Show judgement in review: flatten nested if let pyramids into guard lists, and make each else branch state what leaving means for the caller rather than hiding a missing value.

for a principal

Frame binding as the team's default way to meet absence, so force unwraps stand out as deliberate exceptions, and keep style guidance on guard-first functions consistent across modules.

## What optional binding does An **optional** in Swift is a value of type `Optional<Wrapped>`, usually written `Wrapped?`. It either holds a value or is `nil`. You cannot call `String` methods on a `String?` directly; the compiler first makes you deal with the possibility of `nil`. **Optional binding** is the everyday way to do that: a condition tries to unwrap the optional, and if it holds a value, a new constant (or variable, with `var`) of the **non-optional** type is introduced. Think of a user profile decoded from a backend, where `middleName` and `avatarURL` are often missing: ```swift struct UserProfile { let firstName: String let middleName: String? let lastName: String } ``` Both binding statements below test the same thing. What differs is **where the unwrapped name is visible** and what the failure path must do. ## if let: a value for one block `if let middleName = profile.middleName { … }` runs the braces only when `middleName` is non-`nil`, and inside them `middleName` is a `String`. After the closing brace the name no longer exists. An `else` branch is optional and may do anything, including nothing. Use `if let` when: - the value matters only for a short stretch of code; - the absent case is a normal, alternative path (show the name without a middle name); - you want both outcomes side by side, as in an `if`/`else` that builds two different strings. ## guard let: a value for the rest of the scope `guard let profile = profile else { … }` inverts the shape. The `else` block runs when the optional is `nil`, and it **must leave the current scope**: `return`, `throw`, `break` or `continue` in a loop, or a call to a function that returns `Never`, such as `fatalError(_:file:line:)`. The compiler enforces this; an `else` that only prints is rejected with "'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope". In exchange, the bound name stays available, non-optional, **from the line after the guard to the end of the enclosing scope**. That makes `guard let` the natural fit for early exits: check the inputs a function needs at the top, bail out if any is missing, and write the rest of the function without nesting. ## The Swift 5.7 shorthand Before Swift 5.7 you wrote `if let middleName = middleName`, repeating the name to create an unwrapped shadow. SE-0345 (implemented in Swift 5.7) lets you write `if let middleName`, and the same shorthand works with `guard let`, `if var` and `while let`. Two limits matter in interviews: 1. The shorthand needs a **plain identifier**. `if let profile.middleName` does not compile; the compiler reports "unwrap condition requires a valid identifier". Bind a property with an explicit name: `if let middleName = profile.middleName`. 2. The shorthand still **shadows**: inside the block `middleName` is the unwrapped `String`, and the outer optional of the same name is hidden, not changed. ## Choosing between them | Situation | Prefer | Why | |---|---|---| | Value needed for a few lines | `if let` | Name dies with the block | | Input required for the whole function | `guard let` | Name lives to the end of the scope, no nesting | | Absent value is a normal alternative | `if let` with `else` | Both paths read side by side | | Absent value means stop now | `guard let` | The compiler forces the exit | Both accept a **condition list**: `if let middle = profile.middleName, !middle.isEmpty { … }`. Clauses run left to right, each binding is visible to the clauses after it, and the first failing clause stops the rest. ## Common mistakes - Expecting the bound name to stay optional inside the block; it has the wrapped type. - Writing `if middleName != nil` and then using `middleName` as a `String`; a `nil` check does not narrow the type in Swift, so the value is still `String?` inside the braces. - Nesting three `if let` blocks where one `guard let` list would keep the happy path flat. - Trying the shorthand on a property path or an expression. - Writing a `guard` whose `else` logs and carries on; the compiler stops you, and the fix is to decide what leaving the scope means.

  • Why does the compiler reject a guard let whose else block only prints a message?
    A `guard` promises that the code after it runs only when its condition held. If the `else` block could fall through, the unwrapped name would be used with no value, so the compiler reports "'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope". End the block with `return`, `throw`, `break` or `continue` inside a loop, or a call to a `Never`-returning function such as `fatalError(_:file:line:)`.
  • Can one if statement unwrap two optionals and test a Boolean at the same time?
    Yes. A condition list separates clauses with commas, for example `if let middle = profile.middleName, let url = profile.avatarURL, !middle.isEmpty { … }`. Clauses are evaluated left to right, each binding is visible to the clauses after it, and the body runs only if every clause succeeds. The first clause that fails stops evaluation of the remaining ones.

  • Inside the if let braces the bound name is still an optional.
  • guard let can only appear as the first statement of a function.
  • The Swift 5.7 shorthand also unwraps a property path such as if let profile.middleName.
  • A guard else block can simply log the problem and let execution continue.
  • Checking middleName != nil turns middleName into a String inside the if block.
open as a page

In Swift, what type does an optional chain like profile.manager?.avatarURL return, and how does ?? supply a fallback?

level: middleimportance: must knowfreq 75%

basics

~20 s

An optional chain always returns one level of optional: if any link is nil, the rest of the expression is skipped and the chain is nil. The ?? operator unwraps that result or evaluates its right-hand default, only when needed.

open as a page

In Swift, why does `quantity * unitPrice` fail to compile when quantity is an Int and unitPrice a Double, while `3 * 19.99` compiles?

level: middleimportance: must knowfreq 70%

basics

~20 s

Swift never converts one numeric type to another implicitly, so Int * Double has no matching operator. Literals stay untyped until context picks a type, so 3 becomes a Double in 3 * 19.99. Convert variables explicitly: Double(quantity) * unitPrice.

open as a page

In Swift, why can a String's count, utf8.count and unicodeScalars.count return three different numbers for the same username?

level: middleimportance: must knowfreq 65%

basics

~10 s

String.count counts Characters, and each Character is an extended grapheme cluster that may hold several Unicode scalars; unicodeScalars.count counts those scalars and utf8.count counts encoded bytes, so emoji or accents make all three differ.

open as a page

In Swift, why can't you subscript a String with an Int, and what does index(_:offsetBy:) cost when you truncate a message preview?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Characters in a Swift String have variable width, so reaching the nth one means walking from an end. Swift marks the Int subscript unavailable instead of hiding that cost, and index(_:offsetBy:) is O(n) in the distance it moves.

open as a page

In Swift, how do you label and destructure a tuple such as a file transfer's progress, and when should it become a struct instead?

level: juniorimportance: should knowfreq 45%

basics

~20 s

A Swift tuple groups values into one unnamed type, optionally labeled as (sent: Int64, total: Int64), and let (sent, total) = progress destructures it. Promote it to a struct once it needs Hashable or Codable, methods, or storage.

open as a page

In Swift, how do multiline string literals and raw strings with # delimiters change escaping, indentation and interpolation?

level: juniorimportance: should knowfreq 40%

basics

~20 s

A triple-quoted multiline literal keeps line breaks and strips the indentation of its closing delimiter. Wrapping a literal in # signs makes backslashes and quotes literal; escapes and interpolation then need the same number of #, as in #(name).

open as a page

In Swift, what is Optional underneath its ? sugar, and how do Optional.map and Optional.flatMap differ?

level: middleimportance: should knowfreq 50%

basics

~20 s

Optional is a generic enum with case none, which nil stands for, and case some(Wrapped). Optional.map transforms a present value and wraps the result; Optional.flatMap takes a transform that already returns an optional and does not wrap it again.

open as a page

In Swift, how wide is Int, and why might a file-transfer model store its byte counts as Int64 rather than Int or UInt?

level: middleimportance: should knowfreq 40%

basics

~20 s

Swift's Int matches the platform word size: 64 bits on iPhone, iPad and Mac, 32 bits on 32-bit targets such as arm64_32 watchOS. Int64 keeps byte counts above 2 GiB valid everywhere, and a signed type avoids UInt's conversions and subtraction traps.

open as a page

In Swift, why does slicing a String give you a Substring, and when should you convert it back with String(_:)?

level: middleimportance: should knowfreq 55%

basics

~20 s

Slicing a String returns a Substring that shares the original's storage, so slicing is cheap. Because it keeps that whole storage alive, convert with String(_:) before storing it or passing it to an API that takes String.

open as a page

Why does reading a key from a Swift dictionary typed [String: String?] give String??, and how do you tell a missing key from a stored nil?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Dictionary's subscript returns Value?, and Value is already String?, so the read is String??: nil means the key is missing, .some(nil) means it holds nil. Match both levels, and store nil with updateValue(_:forKey:), because assigning nil removes the key.

open as a page

In Swift, what does a property declared var nameLabel: Label! really declare, and what type does let copy = nameLabel infer?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Label! declares an ordinary Optional<Label> that the compiler may force-unwrap where only a Label type-checks. Where an optional fits, it stays optional, so let copy = nameLabel infers Label?, and an implicit unwrap of nil traps.

open as a page

In Swift, when does Int32(_:) or Int(_:) trap during a numeric conversion, and when should you use init(exactly:), init(clamping:) or init(truncatingIfNeeded:) instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Swift's plain integer initializer traps when the value does not fit, or is NaN or infinite. Use init?(exactly:) to get nil instead, init(clamping:) to saturate at min or max, and init(truncatingIfNeeded:) only when you want the low bits.

open as a page

A Swift payments screen sums prices stored as Double and shows 0.6000000000000001, and Int(price * 100) turns 19.99 into 1998 cents: what is happening, and how should prices be stored?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Double stores most decimal prices inexactly and rounds every operation, so sums drift; Int(_:) then truncates 1998.9999999999998 to 1998. Store money as integer minor units such as Int cents, and round once, deliberately, when a rate is applied.

open as a page

In a Swift chat app, why does == report two usernames equal when their UTF-8 bytes differ, and where does that bite?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Swift's String and Character == compare by Unicode canonical equivalence, so precomposed ë and e plus a combining diaeresis are equal though their bytes differ. Sets agree, but a server or hash that compares bytes does not.

open as a page

As a Swift team lead, what rule would you set for force unwraps and implicitly unwrapped optionals, and how would you enforce it?

level: principalimportance: should knowfreq 35%

basics

~20 s

Treat every ! as a claim that nil is a programmer error: bind, chain or default absence in outside data, force-unwrap only broken invariants, prefer guard with a fatalError message, and keep implicitly unwrapped optionals for late initialisation.

open as a page