3
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {   

    func date(forKey key: String) -> Date? {

        return self[key] as? Date

    }

}

let dictionary: [String : Any] = ["mydate" : Date(), "otherkey" : "Rofl"]

dictionary.date(forKey:"mydate")  // should return a Date? object

// i get the error ambiguous reference to member 'subscript'

How can i make my extension allow me to give a key and use the subscript with not a literal, but a "dynamic" key in the form of String?

Cœur
  • 37,241
  • 25
  • 195
  • 267
bogen
  • 9,954
  • 9
  • 50
  • 89
  • 4
    Just replace `key: String` with `key: Key`. – user28434'mstep Dec 07 '16 at 13:19
  • 4
    Note that `Value: Any` is a redundant constraint. I also see no reason to constrain the `Key` to `ExpressibleByStringLiteral` – what difference does it make if `Key` isn't `ExpressibleByStringLiteral`? – Hamish Dec 07 '16 at 13:26

3 Answers3

4

Remove the unneeded constraints and directly use Key or Value types wherever you see fit.

extension Dictionary {
    func date(forKey key: Key) -> Date? {
        return self[key] as? Date
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
2

Just replace key: String with key: Key:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {

    func date(forKey key: Key) -> Date? {

        return self[key] as? Date

    }

}
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35
1

You can obtain a little sugar syntax by "proxy-ing" the date query to something like this:

struct DictionaryValueProxy<DictKey: Hashable, DictValue, Value> {
    private let dictionary: [DictKey:DictValue]

    init(_ dictionary: [DictKey:DictValue]) {
        self.dictionary = dictionary
    }

    subscript(key: DictKey) -> Value? {
        return dictionary[key] as? Value
    }
}

extension Dictionary {
    var dates: DictionaryValueProxy<Key, Value, Date> { return DictionaryValueProxy(self) }
}

You can then ask the dictionary for it's dates in an seamless way:

let dict: [Int:Any] = [1: 2, 3: Date()]
dict.dates[1]                            // nil
dict.dates[3]                            // "Dec 7, 2016, 5:23 PM"
Cristik
  • 30,989
  • 25
  • 91
  • 127