How to remove value from Dictionary in SWIFT?

0 votes
283 views
asked Mar 3, 2015 in Swift by kalpana (3,995 points)
Hi All

  How to remove value from Dictionary in SWIFT?

1 Answer

0 votes
answered Mar 3, 2015 by john (4,220 points)

Hi Kalpana

 

You can use subscript syntax to remove a key-value pair from a dictionary by assigning a value of nil for that key:

 

  • airports["APL"] = "Apple International"
  • // "Apple International" is not the real airport for APL, so delete it
  • airports["APL"] = nil
  • // APL has now been removed from the dictionary

Alternatively, remove a key-value pair from a dictionary with the removeValueForKey method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:

 

  • if let removedValue = airports.removeValueForKey("DUB") {
  •     println("The removed airport's name is \(removedValue).")
  • } else {
  •     println("The airports dictionary does not contain a value for DUB.")
  • }
  • // prints "The removed airport's name is Dublin Airport."

 

...