Swift example

How to unwrap an optional in Swift

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use if let: if let n = Int(text) { … } runs the block only when there is a value, and guard let n = Int(text) else { return } keeps n for the rest of the function. For a default, write Int(text) ?? 0. The ! in Int(text)! force-unwraps: if the value is nil, the program stops with Fatal error: Unexpectedly found nil while unwrapping an Optional value.

An optional, written Int? or String?, is a box that holds either a value or nil. Swift uses it wherever a value can be missing: Int(text) when the text isn't a number, a dictionary lookup for a key that isn't there, first on an empty array. The compiler won't let you use the box as if it were the value, so you unwrap it first. The sections below cover the safe ways to do that, the compile error you get when you don't, what ! does and why it crashes, and implicitly unwrapped optionals like String!, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1if let: use the value when there is oneRecommended

if let is optional binding: it checks for a value and, if there is one, binds it to a new constant that is a plain Int, not an Int?. The else branch handles nil. Since Swift 5.7 you can write if let name { to unwrap a variable into a constant with the same name. One if can unwrap several optionals and test conditions, separated by commas; the body runs only when every one succeeds. Underneath, an optional is an enum with two cases, .some(value) and .none, which is what nil means.

if_let.swift
// Int(_:) returns Int? because the text may not be a number
let parsed = Int("42")
print(type(of: parsed))
print(String(describing: parsed))
print(String(describing: Int("forty-two")))

// if let: the body runs only when there is a value
if let number = parsed {
    print("number + 1 =", number + 1)
} else {
    print("not a number")
}

// Swift 5.7 shorthand: unwrap into a constant with the same name
let nickname: String? = nil
if let nickname {
    print("Hi, \(nickname)")
} else {
    print("No nickname")
}

// Several bindings and a condition, all in one if
let width = Int("1920")
let height = Int("1080")
if let width, let height, width > height {
    print("landscape \(width)x\(height)")
}

// Optional is an enum: .some(value) or .none (nil)
switch Int("7") {
case .some(let value):
    print("some(\(value))")
case .none:
    print("none")
}

Output

The type of Int("42") prints as Optional<Int>, the long form of Int?. Printed whole it shows as Optional(42), and the failed parse is nil. Inside the if let body, number + 1 = 43 works because number is a plain Int. The nil nickname takes the else branch, the combined check prints landscape 1920x1080, and the switch shows the enum case directly as some(7). The unwrapped constant exists only inside the braces; to keep it afterwards, use guard let.

2guard let: unwrap or leave early

guard let turns the check around: its else block runs when the value is nil and must leave the current scope with return, throw, continue or break. The compiler enforces that, which is what lets the unwrapped constant stay in scope for the rest of the function. That is the practical difference from if let: a function that needs three values unwraps them in three guard lines at the top and then runs without nesting. The guard let name else { shorthand works too.

guard_let.swift
func area(_ widthText: String, _ heightText: String) -> Int? {
    // guard let: leave early when a value is missing
    guard let width = Int(widthText) else {
        print("bad width: \(widthText)")
        return nil
    }
    guard let height = Int(heightText) else {
        print("bad height: \(heightText)")
        return nil
    }
    // width and height are plain Ints from here to the end
    return width * height
}

print(String(describing: area("3", "4")))
print(String(describing: area("3", "four")))

// In a loop, guard pairs with continue
let lines = ["apple=3", "pear", "fig=12"]
var total = 0
for line in lines {
    let parts = line.split(separator: "=")
    guard parts.count == 2, let count = Int(parts[1]) else {
        print("skipping \(line)")
        continue
    }
    total += count
}
print("total:", total)

Output

area("3", "4") passes both guards and returns Optional(12), because the function itself returns Int?. With "four" the second guard prints bad height: four and returns nil. In the loop, "pear" has no =, so the guard prints skipping pear and moves on, and the other two lines add up to total: 15. A guard can mix plain conditions and bindings, as parts.count == 2 does here. Rule of thumb: if let when the value matters only for a few lines, guard let when the rest of the code can't do anything without it.

3A default with ??, and reaching through with ?. and map

Often you don't need a branch at all. The nil-coalescing operator a ?? b gives the value inside a, or b when a is nil, and it chains: x ?? y ?? 0. Optional chaining, a?.b?.c, reads a property or calls a method only when everything to its left has a value, and turns the whole expression into nil otherwise. To transform the value without unwrapping, call map on the optional; use flatMap when the transform itself returns an optional, so you don't end up with an optional inside an optional.

default_chain.swift
struct Address {
    var city: String?
}

struct User {
    var name: String
    var address: Address?
}

let users = [
    User(name: "Ada", address: Address(city: "London")),
    User(name: "Linus", address: Address(city: nil)),
    User(name: "Grace", address: nil),
]

for user in users {
    // ?. stops at the first nil; ?? supplies the fallback
    let city = user.address?.city ?? "unknown"
    print(user.name, "lives in", city)
}

// A chain always gives an optional, even for count (an Int)
let length = users[0].address?.city?.count
print(type(of: length), String(describing: length))

// Dictionary lookups return optionals too
let stock = ["apple": 3, "pear": 0]
print("figs:", stock["fig"] ?? 0)
print("kiwi or apple:", stock["kiwi"] ?? stock["apple"] ?? 0)

// map transforms the value inside; nil stays nil
let input: String? = "21"
let missing: String? = nil
print(String(describing: input.map { $0.count }))
print(String(describing: missing.map { $0.count }))

// flatMap when the transform itself returns an optional
print(String(describing: input.flatMap { Int($0) }))
print(type(of: input.map { Int($0) }))

Output

Linus has an address with no city and Grace has no address at all; the chain gives nil for both, and ?? turns that into unknown. count is a plain Int, but read through a chain it comes back as Optional<Int> Optional(6), so you still unwrap the result. A missing dictionary key falls back to figs: 0, and kiwi or apple: 3 shows ?? trying each side in turn. map gives Optional(2) for the value and leaves nil alone. With flatMap the parse result is Optional(21), while map with the same closure produces the awkward Optional<Optional<Int>>.

4The compile error: “must be unwrapped”

Using an optional where a plain value is needed doesn't compile. This is where most people first meet optionals, and the fix the compiler offers is where ! usually comes from. The program below never runs: it multiplies the Int? from Int(input) by 2, and an optional can't take part in arithmetic because it might be nil.

must_unwrap.swift
let input = "42"
let number = Int(input)
let doubled = number * 2
print(doubled)

Output

The compiler stops with error: value of optional type 'Int?' must be unwrapped to a value of type 'Int' and two notes: coalesce using '??' to provide a default and force-unwrap using '!' to abort execution. The second one is honest about what ! does: it aborts the program when the value is nil. Prefer the first, or an if let: change line 3 to let doubled = (number ?? 0) * 2 and run it again.

5Force unwrapping with !

A ! after an optional, as in Int(text)!, force-unwraps it: you get the plain value, and if there is none the program crashes on the spot. On this page that looks like main/main.swift:2: Fatal error: Unexpectedly found nil while unwrapping an Optional value, followed by a backtrace. The file and line at the front tell you which ! failed; the fix is to unwrap that value with if let, guard let or ?? instead, or to find out why it was nil. Use ! only when nil would be a bug in your own code, such as parsing a literal you typed.

force_unwrap.swift
import Foundation

// A literal you wrote yourself always parses
let port = Int("8080")!
print(port + 1)

// A URL built from a constant string
let url = URL(string: "https://example.com/docs/swift")!
print(url.lastPathComponent)

// After a check the compiler can't see through
let scores = [72, 95, 88]
if !scores.isEmpty {
    print("best:", scores.max()!)
}

// The same without !: nothing can go wrong if the array is empty
if let best = scores.max() {
    print("best:", best)
}

// ! means other things in other places
let ready = false
print(!ready)
print(port != 80)

Output

Each ! here is safe because the value can't be nil: the literal gives 8081 after adding one, the constant URL string is valid (URL needs import Foundation), and max() on a non-empty array prints best: 95. The if let version prints the same and stays safe if someone later empties the array. The last two lines are not unwrapping at all: a leading ! is logical not and != is "not equal". A crash also throws away the output: on this page, lines the program printed before the crash are lost along with it.

6Implicitly unwrapped optionals (String!)

A ! in a type, var title: String!, declares an implicitly unwrapped optional. It is still an optional and starts as nil, but every use force-unwraps it for you. It exists for values that can't be set in init yet are always set before anyone reads them: a property filled by a setup method, or an @IBOutlet connected when a storyboard loads. You really do know there's a value, just not at the moment the object is created. If that turns out to be wrong, the crash reads Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value.

implicitly_unwrapped.swift
final class Report {
    // Set in load(), always before use, so declared with !
    var title: String!

    func load() {
        title = "Q4 sales"
    }
}

let report = Report()
print(report.title == nil)
report.load()

// Used like a plain String: no unwrapping needed
print(report.title.uppercased())
print(report.title.count)

// Copied into a new constant, it is an ordinary optional again
let copy = report.title
print(type(of: copy))

// if let still works when you are not sure
if let title = report.title {
    print("title:", title)
}

Output

Before load() the property is nil (true), and you can compare it with nil without crashing. After it, report.title.uppercased() gives Q4 SALES with no unwrapping. Assigned to a new constant, the value does not stay implicitly unwrapped: its type prints as Optional<String>, so the convenience ends at the property. In new code, prefer a non-optional with a value set in init, or a plain String? unwrapped with if let; keep ! types for the two-step setup cases they were made for.

7Which should you use?

MethodWhen nilThe value afterBest for
if let x { … }Runs elseInside the bracesCode that needs the value for a few lines
guard let x else { … }Must exit the scopeRest of the scopeValues a function needs before it can go on
x ?? fallbackUses the fallbackPlain valueA sensible default exists
a?.b?.cWhole chain is nilStill optionalReading through optional properties
x.map / x.flatMapStays nilStill optionalTransforming without unwrapping
x!CrashesPlain valueValues that are nil only if your code has a bug
var x: T!Crashes on useUsed like TProperties set after init, outlets

Frequently asked questions

What does an exclamation mark mean in Swift?

It depends on where it sits. After an optional value, x! force-unwraps it and crashes if it is nil. In a type, String! declares an implicitly unwrapped optional. as! is a forced cast and try! calls a throwing function and crashes on an error. Before a Bool, !ready is logical not, and != means not equal. Only the first two have to do with optionals.

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

A ! (or an implicitly unwrapped T! property, which says "implicitly unwrapping" in the message) met a nil value, and Swift stopped the program rather than continue without a value. The text in front of it gives the file and line, like main/main.swift:2: here. Replace that ! with if let, guard let or ??, or find out why the value was nil when you expected one.

Why create implicitly unwrapped optionals if you know there is a value?

Because you know it only after setup, not when the object is created. A property filled by a setup method or an @IBOutlet connected when a storyboard loads cannot get its value in init, so it starts as nil, but every read happens after it is set. String! lets that code skip unwrapping. If a read happens too early, it crashes with "Unexpectedly found nil while implicitly unwrapping an Optional value".

What is the difference between guard let and if let?

With if let, the unwrapped constant exists only inside the braces and the else branch is optional. With guard let, the else block is required, must leave the scope (return, throw, continue or break), and the constant stays available for the rest of the scope. Use guard at the top of a function for values it cannot work without, and if let when the value matters for a few lines.

Why does print show Optional(42) instead of 42?

Because the value is still an optional: print(Int("42")) prints Optional(42), and the compiler warns "expression implicitly coerced from 'Int?' to 'Any'". Unwrap it first with if let, give a default with ?? 0, or, when you really want the optional form, print String(describing: value), which silences the warning.

How do I check whether an optional is nil without unwrapping it?

Compare it: if value == nil or if value != nil. That only tells you whether there is a value; to use it, you still unwrap. When you need both, if let value does the check and the unwrap in one step, so prefer it over if value != nil followed by value!.

What is the difference between ?. and !. in Swift?

user?.address is optional chaining: if user is nil, the whole expression is nil and nothing else happens. user!.address force-unwraps user first, so a nil user crashes with "Unexpectedly found nil while unwrapping an Optional value". Use ?. and handle the nil at the end with ?? or if let.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground