Skip to content

Instantly share code, notes, and snippets.

@narfdotpl
Created January 23, 2015 07:05
Show Gist options
  • Save narfdotpl/78860a9ce5dbc3e19633 to your computer and use it in GitHub Desktop.
Save narfdotpl/78860a9ce5dbc3e19633 to your computer and use it in GitHub Desktop.
Swift job interview idea: implement Dictionary.map

Swift job interview idea: implement Dictionary.map

https://twitter.com/narfdotpl/status/558348210079809536

First try on a piece of paper

extension Dictionary {
    func map<A: Hashable, B>(f: (Hmm.Key, Hmm.Value) -> (A, B)) -> [A: B] {
        var d: [A: B] = [:]

        for (k, v) in map(self, f) {
            d[k] = v
        }

        return d
    }
}
  • I thought Hashable is needed. Turns out it's not.
  • I didn't know how to reference original key and value types. Turns out they're just Key and Value.
  • I didn't see recursion in map(self, f). :p

With a compiler

extension Dictionary {
    func map<A, B>(f: (Element) -> (A, B)) -> [A: B] {
        var d: [A: B] = [:]

        for (k, v) in Swift.map(self, f) {
            d[k] = v
        }

        return d
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment