NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Building a generic Dictionary extension...

Forums > Swift

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!

   

Two solutions came as replies on my question in stackoverflow:

1 - As an extension:

extension Dictionary {

    mutating func add<T>(_ element: T, toArrayOn key: Key) where Value == [T] {
        self[key] == nil ? self[key] = [element] : self[key]?.append(element)
    }
}

2 - Using a default argument:

dictionary[key, default: []].append(element)

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.