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

Brian Greeson
Brian Greeson
4,034 Points

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
207,980 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.

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