Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
由于类型转换错误,无法对JSON数组分组_Json_Swift - Fatal编程技术网

由于类型转换错误,无法对JSON数组分组

由于类型转换错误,无法对JSON数组分组,json,swift,Json,Swift,我有一个API,它返回一个字典数组,我正试图使用Swift的dictionary(grouping:)函数按每个项目中的date键对其进行分组。 JSON如下所示: [ { "date": "2018-12-12", "name": "abc" }, { "date": "2018-12-12", "name": "def" }, { "date": "2018-12-13", "name": "def" }, ... ] 我有以下生成编译错误的swift代码:

我有一个API,它返回一个字典数组,我正试图使用Swift的
dictionary(grouping:)
函数按每个项目中的
date
键对其进行分组。 JSON如下所示:

[
    { "date": "2018-12-12", "name": "abc" },
    { "date": "2018-12-12", "name": "def" },
    { "date": "2018-12-13", "name": "def" },
    ...
]
我有以下生成编译错误的swift代码:

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

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

我非常困惑,因为
变量的类型显然是
[String:AnyObject]
,我可以通过执行
po json[0][“date”]

在调试器中索引到json,因为您的代码自相矛盾。当你说

let groupedByDate = Dictionary(grouping: json, by: {
    (item) -> String in
您正在签订一个合同,将从此闭包返回一个字符串

但是当你说

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

您返回的是AnyObject,不是字符串。

谢谢!这个错误有些误导,或者我只是误解了它。我将整个表达式转换为一个字符串,它可以工作。我能够将所有内容压缩为:
让groupedByDate=Dictionary(grouping:json,by:{$0[“date”]as!String})
你不会让我为Swift编译器错误消息辩护的!我想我可以弄清楚编译器一定在想什么,但不值得担心。
return (item as! [String:AnyObject])["date"]