Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift Collections and Control Flow Dictionaries in Swift Modifying a Dictionary

Can we store nil as a value in a dictionary?

The video mentioned that assigning nil as a value in a dictionary will tell swift to remove this value from the dictionary. What if we want to store a key will the value of nil, is this not possible?

2 Answers

Steven Parker
Steven Parker
231,184 Points

There are a few ways:

  • create the dictionary with an optional type
  • set it using   <yourdict>.updateValue(nil, forKey: <yourkey>)
  • cast it to a different type:   <yourdict>[<yourkey>] = nil as String?

But also consider why you'd want this, since it makes it appear that the key doesn't exist. If you attempt to access a key that isn't there, you get back "nil" anyway.

Jhoan Arango
Jhoan Arango
14,575 Points

Hi Brian,

Storing nil in a dictionary serves no purpose, nil does nothing, nor can you do anything with it. So, let's say you call a key that has no value, you will be returned nil anyway.

When you request a value from a dictionary, a dictionary returns an optional value, meaning this value may or may not exist, if it does not exist, then you get nil. So technically you will end up with what you are looking for, a nil value on a key.

/// A dictionary of numbers
let numbersDictionary: [String: Int] = ["one" : 1, "two" : 2, "three": 3]

/// Here we are safely unwrapping a nil value
/// since we do not have a "four" key value pairs.
if let number = numbersDictionary["four"] {

// This will only print if there is a value for the key "four", otherwise it will
// be nil.
    print("This is the number: \(number)") // This is the number 4
}

Hope this makes sense