-5

In my Swift3 code I have an array:

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

Later on I want to add another array to this array, I thought I could just do:

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

but I'm getting error here:

Type Any? has no subscript members

How can I add that array to my previously declared array fields?

user3766930
  • 5,629
  • 10
  • 51
  • 104
  • 4
    Please attempt to some [basic searching on the error](http://stackoverflow.com/search?q=%5Bswift%5D+Type+Any%3F+has+no+subscript+members) before posting. – rmaddy Apr 25 '17 at 18:00

1 Answers1

5

Since your dictionary is declared as [String : Any], the compiler doesn't know that the value for "fields" is actually a dictionary itself. It just knows that it's Any. One very simple way to do what you're trying is like this:

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

This will just do nothing if eventParams["fields"] is nil, or if it's not actually [String : Any].

You can also do this in a couple steps to allow for troubleshooting later on like this:

//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
creeperspeak
  • 5,403
  • 1
  • 17
  • 38
  • Thanks man, I tried your solution (the first one so far) and I'm getting the following error: `Cannot assign to immutable expression of type Any?` :( – user3766930 Apr 25 '17 at 17:56
  • I also tried the 2nd approach, and the middle line esp. `eventParams["fields"]["user_location"]` causes error same as before, `Type Any? has no subscript members` – user3766930 Apr 25 '17 at 17:58
  • @user3766930 I'm sorry - I had a mistake in there. Try the 2nd option again based on my edits. – creeperspeak Apr 25 '17 at 18:01
  • Thanks for your patience :) However, right now I see this error http://imgur.com/XpbUxJW , is there some typo maybe? – user3766930 Apr 25 '17 at 18:06
  • @user3766930 My bad again - sorry. Try one more time. – creeperspeak Apr 25 '17 at 18:08