UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

3      

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)

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.