2017-04-25 49 views
-5

在我Swift3代码,我有一个数组:类型任何有没有下的成员,同时增加数组[字符串:任何在Swift3

var eventParams = 
[ "fields" : 
     [ "photo_url":uploadedPhotoURL, 
      "video_url":uploadedVideoURL 
     ] 
] 

后来我要到另一个阵列添加到这个阵列中,我想我可能只是做:

eventParams["fields"]["user_location"] = [ 
      "type":"Point", "coordinates":[appDelegate.longitude, appDelegate.latitude] 
     ] 

但我发现了错误的位置:

Type Any? has no subscript members 

哪有我的广告d那个数组到我之前声明的数组fields

+4

请尝试一些[基本搜索上的错误(http://stackoverflow.com/search? q =%5Bswift%5D + Type +任何%3F +都有+ no +下标+成员)。 – rmaddy

回答

5

由于您的字典被声明为[String : Any],因此编译器不知道“字段”的值实际上是字典本身。它只知道它是Any。一个非常简单的方法你想的是这样的:

(eventParams["fields"] as? [String : Any])?["user_location"] = [ 
     "type":"Point", "coordinates":[appDelegate.longitude, appDelegate.latitude] 
    ] 

这将只是做什么,如果eventParams["fields"]是零,或者如果它实际上不是[String : Any]

你也可以做到这一点在几个步骤,以便进行故障排除以后这样的:

//Get a reference to the "fields" dictionary, or create a new one if there's nothig there 
var fields = eventParams["fields"] as? [String : Any] ?? [String : Any]() 

//Add the "user_location" value to the fields dictionary 
fields["user_location"] = ["type":"Point", "coordinates":[appDelegate.longitude, appDelegate.latitude]] 

//Reassign the new fields dictionary with user location added 
eventParams["fields"] = fields 
+0

谢谢你,我尝试了你的解决方案(到目前为止的第一个),我得到以下错误:'不能分配给任何类型的不可变表达式?':( – user3766930

+0

我也尝试了第二种方法,并且中间行esp 。'eventParams [“fields”] [“user_location”]'导致错误与之前一样,'Type Any?没有下标成员' – user3766930

+0

@ user3766930对不起 - 我有一个错误。对我的编辑 – creeperspeak

相关问题