0 votes
asked in Swift by (4k points)
Hi All

  How to remove value from Dictionary in SWIFT?

1 Answer

0 votes
answered by (4.2k 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."