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

use*_*930 -5 swift swift3

在我的Swift3代码中,我有一个数组:

var eventParams =
[    "fields" :
        [ "photo_url":uploadedPhotoURL,
            "video_url":uploadedVideoURL
        ]
]
Run Code Online (Sandbox Code Playgroud)

后来我想在这个数组中添加另一个数组,我想我可以做到:

eventParams["fields"]["user_location"] = [
            "type":"Point", "coordinates":[appDelegate.longitude, appDelegate.latitude]
        ]
Run Code Online (Sandbox Code Playgroud)

但我在这里得到错误:

Type Any? has no subscript members
Run Code Online (Sandbox Code Playgroud)

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

cre*_*eak 5

由于您的字典被声明为[String : Any],编译器不知道"fields"的值实际上是字典本身.它只是知道它Any.一个非常简单的方法来做你正在尝试的是这样的:

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

如果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
Run Code Online (Sandbox Code Playgroud)