---
title: "Swift expected nil, not <nil>"
source: "/writing/swift-expected-nil-not-nil/"
---

Article

# Swift expected nil, not <nil>

Sean Berry

May 4, 2019

My unit test failed. It wanted a `nil` but got a `<nil>`. My initial reaction was to accuse my computer of being dumb. Are you expecting a different type of `nil` from me? There's only one `nil`, and its name is `nil`.

But hold up. Computers aren't sophisticated enough to prank us. What did I do wrong?

## The Dictionary Problem

It's standard in Swift to unwrap an optional with `if let`. Why did I receive a `nil` on line 3?

There's a clue on line 8. When I explicitly set `first` to be `nil`, the unwrap operation behaves as expected. There really must be a different kind of `nil` here.

## How Dictionary fetches values

`Dictionary` wraps the value in an optional before handing it to you.

This is all good and expected. My problem came in because I was setting my value type as `Any?` instead of `Any`. Swift was double wrapping my value!

## Setting a key to nil

When you set a key to `nil` in a Dictionary it removes that key/value pair for you. That's why line 8 above behaves as expected.

If you want to explicitly set your value to `nil` in a Dictionary with an optional value type, you must wrap it yourself first.

Swift was doing this extra step automatically when I first created my dictionary with `var dict: [String: Any?] = ["first", nil]` -- it wrapped that nil for me behind the scenes.

## Don't do this!

I ended up refactoring my Dictionary to not use an optional for its value. The fewer quirky rules one has to keep in mind the better. If I got confused from my own code, what would happen to another developer jumping in? For a longer meditation on this idea, [check out Tyler Johnson's essay on code design](/writing/applying-design-concepts-to-code) .

Code should present itself like a political cartoon -- full of blunt metaphors with helpful labels and no subtlety.

_Sean judges what code looks like at_ [_Livefront_](http://www.livefront.com) _._

-   Sean Berry

    Software Engineer

    Sean Berry

### Tags

[Digital Engineering](/insights/all/?topic=digital-engineering) [Mobile Apps](/insights/all/?topic=mobile-apps)

### Share

-   Copied

## View these next.

[See all](/insights/all/?type=writing)

-   [

    Article

    How To Sabotage Your Project Using Inconsistency

    Collin Flynn

    ](/writing/how-to-sabotage-your-project-using-inconsistency/)
-   [

    Article

    Unit Testing race conditions by creating chaos (Swift)

    Sean Berry

    ](/writing/unit-testing-race-conditions-by-creating-chaos-swift/)
-   [

    Article

    UIApplicationDelegate call sequence reference

    Sean Berry

    ](/writing/uiapplicationdelegate-call-sequence-reference/)
