Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremiasdsa/bff0f5e9eb83b7506cf43f25c04fdcf9 to your computer and use it in GitHub Desktop.
Save jeremiasdsa/bff0f5e9eb83b7506cf43f25c04fdcf9 to your computer and use it in GitHub Desktop.
Swift: Append an element to an array in a dictionary value, creating the array/value if needed
import Foundation
extension Dictionary where Value: RangeReplaceableCollection {
public mutating func append(element: Value.Iterator.Element, toValueOfKey key: Key) -> Value? {
var value: Value = self[key] ?? Value()
value.append(element)
self[key] = value
return value
}
}
var books: [String: [String]] = [
"Phillip K Dick": [
"Do Androids Dream of Electric Sheep?",
"The Man in the High Castle",
],
"Cory Doctorow": [
"Down and Out in the Magic Kingdom",
"Makers",
]
]
books.append(element: "Eastern Standard Tribe", toValueOfKey: "Cory Doctorow")
books
/*
[
"Phillip K Dick": [
"Do Androids Dream of Electric Sheep?",
"The Man in the High Castle",
],
"Cory Doctorow": [
"Down and Out in the Magic Kingdom",
"Makers",
"Eastern Standard Tribe",
]
]
*/
books.append(element: "Parable of the Sower", toValueOfKey: "Octavia Butler")
books
/*
[
"Phillip K Dick": [
"Do Androids Dream of Electric Sheep?",
"The Man in the High Castle",
],
"Cory Doctorow": [
"Down and Out in the Magic Kingdom",
"Makers",
"Eastern Standard Tribe",
],
"Octavia Butler": [
"Parable of the Sower",
]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment