Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
222,216 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