Swift
Dictionary
Key-value
Remove
Programming

How to remove a key-value pair from swift dictionary?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Removing an entry from a Swift dictionary is simple, but there are two idiomatic ways to do it and they behave slightly differently. The usual choices are removeValue(forKey:) when you care about the removed value and assigning nil through subscript syntax when you only want the key gone.

Core Sections

The standard method: removeValue(forKey:)

The most explicit API is removeValue(forKey:). It mutates the dictionary and returns the value that was removed, or nil if the key was not present.

swift
1var scores = [
2    "Ana": 10,
3    "Ben": 7,
4    "Cara": 12
5]
6
7let removed = scores.removeValue(forKey: "Ben")
8
9print(removed as Any)  // Optional(7)
10print(scores)          // ["Ana": 10, "Cara": 12]

That return value is useful when removal and retrieval happen together, such as popping an item out of a lookup table.

The shorter form: assign nil

Swift dictionaries also support removal through the subscript setter. Setting a value to nil removes the key entirely.

swift
1var settings = [
2    "theme": "dark",
3    "language": "en"
4]
5
6settings["theme"] = nil
7
8print(settings)  // ["language": "en"]

This is concise and idiomatic when you do not need the old value. It is especially convenient in update flows where dictionary assignment is already being used.

Make sure the dictionary is mutable

Removal only works on a dictionary declared with var. A dictionary declared with let is immutable.

swift
1var mutableDict = ["a": 1, "b": 2]
2mutableDict.removeValue(forKey: "a")
3
4let immutableDict = ["x": 9, "y": 8]
5// immutableDict.removeValue(forKey: "x")  // compile-time error

If the compiler complains about mutation, check the declaration before debugging anything else.

Handling the optional return safely

Because a missing key returns nil, the removed value should be treated as optional.

swift
1var inventory = [
2    "apples": 5,
3    "oranges": 3
4]
5
6if let count = inventory.removeValue(forKey: "apples") {
7    print("Removed \(count) apples")
8} else {
9    print("Key was not present")
10}

This pattern avoids forced unwrapping and clearly documents that the key may or may not exist.

When to choose each style

Use removeValue(forKey:) when:

  • you want the removed value
  • you want the code to read explicitly as a removal
  • you are branching on whether the key existed

Use dict[key] = nil when:

  • you only need deletion
  • the code is already expressed as dictionary assignment
  • brevity improves readability

Both are correct. The better choice depends on whether the old value matters.

If you need to remove several keys, gather them first and then mutate the dictionary in a separate pass. That keeps the code predictable and avoids collection-mutation mistakes during iteration.

Common Pitfalls

  • Trying to remove from a dictionary declared with let instead of var.
  • Forgetting that removeValue(forKey:) returns an optional and assuming the key must exist.
  • Using deletion syntax on the wrong key type, such as passing an Int key to a [String: Value] dictionary.
  • Expecting dict[key] = nil to leave the key with a null-like value; in Swift it removes the entry.
  • Mutating a dictionary while iterating over it without first collecting the keys that should be removed.

Summary

  • 'removeValue(forKey:) is the clearest way to remove a key-value pair from a Swift dictionary.'
  • It returns the removed value as an optional, which is useful when the previous value matters.
  • 'dict[key] = nil is a shorter, equally valid way to delete an entry.'
  • Dictionary removal requires a mutable var dictionary.
  • Choose the style based on whether you need the removed value or just want to delete the key.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.