Swift: Dictionary filtering
Video: Swift: Dictionary filtering by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: Dictionary filtering
Filtering dictionaries in Swift allows you to create a new dictionary containing only the key-value pairs that meet certain conditions. This is useful for extracting relevant data or cleaning up dictionaries based on your criteria.
Code
// Original dictionary with fruit names and their quantities
let fruitInventory = [
"apple": 10,
"banana": 5,
"orange": 8,
"pear": 0
]
// Filter dictionary to include only fruits with quantity greater than 0
let availableFruits = fruitInventory.filter { (key, value) in
value > 0
}
// availableFruits is ["apple": 10, "banana": 5, "orange": 8]
print(availableFruits)
// You can also filter by keys, for example fruits starting with "a"
let fruitsStartingWithA = fruitInventory.filter { key, _ in
key.hasPrefix("a")
}
// fruitsStartingWithA is ["apple": 10]
print(fruitsStartingWithA)
Key Points
- The filter method on dictionaries returns a dictionary containing only the key-value pairs that satisfy the given condition.
- You can filter based on keys, values, or both using a closure that takes (key, value) as parameters.
- Filtering does not modify the original dictionary but returns a new filtered dictionary.
- Use conditions like value comparisons or string methods on keys to customize filtering.