serhanaksut
serhanaksut

Reputation: 648

How to add a new key but not add value to dictionary in swift?

I have been trying to add a new key to my dictionary in swift which was declared as Dictionary<BagItem, Array<BagItem>>. However, I could not achieve this. I have been trying to do it in a method like this:

static func AddMainItem(item: BagItem)
{
   self.bag[item] = Array<BagItem>()
}

Note: I have been trying to add only key not add a value. I have debugged the code and I saw that it always updates previous key with new key.

Thank you for your answers Best regards

Upvotes: 0

Views: 2153

Answers (1)

Steve Rosenberg
Steve Rosenberg

Reputation: 19524

You won't be able to. You should just update it with an empty string "" for example. Assigning nil to a dictionary entry is how you remove a key. Put this in a playground:

var dictionary = [String:String]()
dictionary["test"] = nil
println(dictionary)
// [:]

dictionary["test"] = ""
println(dictionary)
// [test: ]

Upvotes: 5

Related Questions