Adam Langsner
Adam Langsner

Reputation: 1286

Cannot group JSON array because of typecasting error

I have an API that returns an array of dictionaries and I'm trying to group it by the date key in each item using Swift's Dictionay(grouping:) function. The JSON looks like this:

[
    { "date": "2018-12-12", "name": "abc" },
    { "date": "2018-12-12", "name": "def" },
    { "date": "2018-12-13", "name": "def" },
    ...
]

I have the following swift code that generates a compilation error:

let json = response.result.value as! Array<[String:AnyObject]>
let groupedByDate = Dictionary(grouping: json, by: { (item) -> String in
    return (item as! [String:AnyObject])["date"]
})

When I compile I get this error:

Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'

and this warning:

Cast from '_' to unrelated type '[String : AnyObject]' always fails

I'm very confused because the item variable is clearly of type [String:AnyObject] and I am able to index into the json in the debugger by doing po json[0]["date"].

Upvotes: 2

Views: 50

Answers (1)

matt
matt

Reputation: 535557

Your code contradicts itself. When you say

let groupedByDate = Dictionary(grouping: json, by: {
    (item) -> String in

you are making a contract that you will return a String from this closure.

But when you then say

return (item as! [String:AnyObject])["date"]

you are returning an AnyObject, not a String.

Upvotes: 2

Related Questions