I want to get Addresses from profile dictionary,but I got the error "type any? has no subscript members"
var address:[[String : Any]] = [["Address": "someLocation", "City": "ABC","Zip" : 123],["Address": "someLocation", "City": "DEF","Zip" : 456]]
var profile:[String : Any] = ["Name": "Mir", "Age": 10, "Addresses": address]
profile["Addresses"][0] <-----------------type any? has no subscript members
How can I fix it and get the address? Thanks a lot.
I agree that if you rethink your design as suggested earlier. For discussion sake you can perform the following to achieve what you are seeking.
You should re-think how you've chosen to construct
adress
andprofile
; see e.g. Alexander Momchliov's answer.For the technical discussion, you could extract the
Any
members ofprofile
that you know to contain[String: Any]
dictionaries wrapped in anAny
array; by sequential attempted type conversion ofprofile["Addresses"]
to[Any]
followed by element by element (attempted) conversion to[String: Any]
:or, without an intermediate step ...
But this is just a small lesson in attempted typed conversion (-> don't do this).
When you subscript profile with
"Addresses"
, you're getting anAny
instance back. Your choice to useAny
to fit various types within the same array has caused type erasure to occur. You'll need to cast the result back to its real type,[[String: Any]]
so that it knows that theAny
instance represents anArray
. Then you'll be able to subscript it:This is very clunky though, and it's not a very appropriate case to be using Dictionaries in the first place.
In such a situation, where you have dictionaries with a fixed set of keys, structs are a more more appropriate choice. They're strongly typed, so you don't have to do casting up and down from
Any
, they have better performance, and they're much easier to work with. Try this: