I'm trying to find a nice, clean and generic way of extending dictionaries so that I can add an element to an array stored in the dictionary but without having to explicitly check if the key for that entry exists.
In other words, let the extension do the key-checking; if it does exist, then add the element to the array enclosed in that key, if it doesn't exist, then create the key by storing a new array with that element.
The code that I use now goes like this:
dictionary[key] == nil ? dictionary[key] = [element] : dictionary[key]?.append(element)
But I would love to write something like:
dictionary.add(element, toArrayOn: key)
The extension would look something like this:
extension Dictionary {
mutating func add(element: SomeElement, toArrayOn key: Key) {
// Check if self[key] exisists:
// If self[key] != nil, check if the value is Array<SomeElement>, if so append the element to the Array, if not throw an error.
// If self[key] == nil, make an empty Array<SomeElement> and insert the element.
}
}
}
I recognize this might be a bit of a stretch but I find it fun to write these sort of extensions that help clean up code. I'm also starting to catch up with the idea of deciding a specific code syntax and then figuring out how can it be accomplished.
Any thoughts on this would be very welcome!