How to add nil value to Swift Dictionary?

前端 未结 9 480
春和景丽
春和景丽 2021-01-31 01:20

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

相关标签:
9条回答
  • 2021-01-31 02:03
    postDict[surname]=nil
    

    When you use subscript to set nil. It deletes the key if exists. In this case key surname will be removed from dictionary if exists.

    To set value as nil, there are certain ways.

    postDict.updateValue(nil, forKey: surname)
    

    or

    let anyObjectNil : AnyObject? = nil
    postDict[surname] = anyObjectNil
    

    or

    postDict[surname] = nil as AnyObject?
    
    0 讨论(0)
  • 2021-01-31 02:07

    You can use the updateValue method:

    postDict.updateValue(nil, forKey: surname)
    
    0 讨论(0)
  • 2021-01-31 02:08
    postDict[surname] = Optional<AnyObject>(nil)
    
    0 讨论(0)
提交回复
热议问题