How to add nil value to Swift Dictionary?

33,798

Solution 1

How to add nil value to Swift Dictionary?

Basically the same way you add any other value to a dictionary. You first need a dictionary which has a value type that can hold your value. The type AnyObject cannot have a value nil. So a dictionary of type [String : AnyObject] cannot have a value nil.

If you had a dictionary with a value type that was an optional type, like [String : AnyObject?], then it can hold nil values. For example,

let x : [String : AnyObject?] = ["foo" : nil]

If you want to use the subscript syntax to assign an element, it is a little tricky. Note that a subscript of type [K:V] has type V?. The optional is for, when you get it out, indicating whether there is an entry for that key or not, and if so, the value; and when you put it in, it allows you to either set a value or remove the entry (by assigning nil).

That means for our dictionary of type [String : AnyObject?], the subscript has type AnyObject??. Again, when you put a value into the subscript, the "outer" optional allows you to set a value or remove the entry. If we simply wrote

x["foo"] = nil

the compiler infers that to be nil of type AnyObject??, the outer optional, which would mean remove the entry for key "foo".

In order to set the value for key "foo" to the AnyObject? value nil, we need to pass in a non-nil outer optional, containing an inner optional (of type AnyObject?) of value nil. In order to do this, we can do

let v : AnyObject? = nil
x["foo"] = v

or

x["foo"] = nil as AnyObject?

Anything that indicates that we have a nil of AnyObject?, and not AnyObject??.

Solution 2

You can use the updateValue method:

postDict.updateValue(nil, forKey: surname)

Solution 3

As documented in here, setting nil for a key in dictionary means removing the element itself.

If you want null when converting to JSON for example, you can use NSNull()

var postDict = Dictionary<String,AnyObject>()
postDict["pass"]=123
postDict["name"]="ali"
postDict["surname"]=NSNull()

let jsonData = NSJSONSerialization.dataWithJSONObject(postDict, options: NSJSONWritingOptions.allZeros, error: nil)!
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
// -> {"pass":123,"surname":null,"name":"ali"}

Solution 4

postDict[surname] = Optional<AnyObject>(nil)

Solution 5

You can use the Optional type

var postDict = ["pass": 123, "name": "ali", "surname": Optional()]
Share:
33,798

Related videos on Youtube

yatanadam
Author by

yatanadam

Updated on September 16, 2020

Comments

  • yatanadam
    yatanadam over 3 years

    I have made a request to my server in my app. And posted data something like this.Server side is waiting for all parameters even they are nil. But i couldn't add nil values to dictionary.

     var postDict = Dictionary<String,AnyObject>
     postDict[pass]=123
     postDict[name]="ali"
     postDict[surname]=nil // dictionary still has only pass and name variables.
    

    Is there a way to add nil value to dictionary ?

    • The Paramagnetic Croissant
      The Paramagnetic Croissant over 9 years
      When you assign nil to a key, it will return nil next time you access that key (because it removes the object and the removed object is not there). If you want to represent a non-nil null value, you can use NSNull().
    • Jérôme Teisseire
      Jérôme Teisseire over 9 years
      use [NSNull null] or nothing.
    • Abizern
      Abizern over 9 years
      This isn't even a swift question; putting NSNull instances in a dictionary to represent empty values is part of Foundation.
  • Franklin Yu
    Franklin Yu about 8 years
    This solution is so much more Swifty than NSNull()!
  • Raginmari
    Raginmari almost 8 years
    It's a little easier to use and more readable if you define this "Null" object as a constant:static let NullObject: AnyObject?? = Optional(nil)
  • ramazan polat
    ramazan polat over 7 years
    Dont know why this is downvoted but this is the best way to do it imho.
  • RenniePet
    RenniePet over 7 years
    Whose bright idea was it that assigning nil to a dictionary entry means remove the entry, even when nil is a valid entry when the dictionary is defined as having AnyObject? or Any? entries? That just cost me several hours and lowered my opinion of Swift a couple of notches.
  • Franklin Yu
    Franklin Yu over 7 years
    First line should be var dict = [Int: Int?](). It's a definition, not just a declaration.
  • Andrea
    Andrea about 7 years
    The correct answer is the one from Guiller, by setting nil a value using subscript you remove the value anche the key, while using the function updateValue you can set the value to nil while keeping the key.
  • Bartłomiej Semańczyk
    Bartłomiej Semańczyk over 6 years
    This is the best answer I have ever seen on SA. You should be gifted with 1 million battles of wine;) I have created a bounty and I will award it to you within 24 hours;)
  • Martin R
    Martin R over 6 years
    @BartłomiejSemańczyk: Then you should have chosen "One or more of the answers is exemplary and worthy of an additional bounty." as the bounty reason. Now it looks as if you are looking for another/better answer.
  • Bartłomiej Semańczyk
    Bartłomiej Semańczyk over 6 years
    @MartinR you are right, I would change the reason of bounty but I cannot. Nice learn to me;)
  • Jakub Truhlář
    Jakub Truhlář about 6 years
    Good point. It's confusing, but the point is indeed use = nil as Foo?.
  • Max
    Max over 5 years
    In most (all?) cases you don't even need the <AnyObject>. It should be able to infer the type.
  • Li Jin
    Li Jin over 4 years
    This is a very right answer for setting nil value for a key.
  • user2101384
    user2101384 about 3 years
    x["foo"] = nil will delete the entry "foo". x["foo"]! = nil will se the value of the entry "foo" to nil. x["bar"] = nil will not insert any entry. x["bar"]! = nil will blow up. x.updateValue( nil, forKey: "bar" ) will add entry "bar" to x with value nil, as pointed in the @Guiller answer.
  • user2101384
    user2101384 about 3 years
    x["foo"] = nil as Any? also works. But I think updateValue(nil, forKey: "foo") is easier to understand for people who is junior or getting started with swift.