在Swift3中向[String:Any]添加数组时,Type Any没有下标成员

时间:2017-04-25 17:37:55

标签: swift 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

如何将该数组添加到我之前声明的数组fields

1 个答案:

答案 0 :(得分:5)

由于您的字典被声明为[String : Any],编译器不知道“fields”的值实际上是字典本身。它只知道它是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