Array.map() produces '[T]', not the expected contextual result type '[String: Any?]'

Liau Jian Jie picture Liau Jian Jie · Feb 4, 2017 · Viewed 8.3k times · Source

I'm writing an extension to bridge the dictionary values between FirebaseDatabase and Eureka.

private extension Dictionary {
    func firebaseFriendlyDictionary() -> [String: Any?] {
        return self.map({ (key: String, value: Any?) -> (String, Any?) in
            if value is NSDate {
                return (key, (value as! NSDate).timeIntervalSince1970)
            }
            return (key, value)
        })
    }
}

But I get thrown this error when I try to build:

map produces '[T]', not the expected contextual result type '[String: Any?]'

Answer

Losiowaty picture Losiowaty · Feb 4, 2017

Your problem lies with the fact, that map always returns an Array, even when applied on a Dictionary. Your error message basically means, that you declared your method as returning a Dicitonary, but the statement inside returns an Array ([T] - means an Array with objects of some type T). In your case, the array returned by map will contain tuples (more about them here). In this case it looks like a key value pair, but its not equivalent to a key-value pair inside a Dictionary. Basically, tuples enable you to return more than one value/object from method. You can think of them as of anonymous structures.

In my opinion, there is no need to use a map to accomplish what you need - the solution provided by Mr. Xcoder is the way to go.