Search code examples
swiftswift-extensions

How to make an extension for dictionary that allows use of the subscript with a dynamic key?


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?


Solution

  • 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
        }
    }