Bill L Bill L - 2 months ago 6
iOS Question

Can't cast from Dictionary value to Array

No idea why this won't work. The value of this dictionary is a key, yet whenever I try to cast to an array, I get a multitude of errors. Here's what I've tried, with the error I get following each example (in all examples,

parameters
is type
[String : Any]
:

let paramsArray = parameters["inputVO"] as AnyObject
if let array = paramsArray as? Array {

}


Error:
Generic parameter 'Element' could not be inferred in cast to 'Array<_>'


if let array = parameters["inputVO"] as? Array {

}


Error:
Ambiguous reference to member 'subscript'


I'm not sure what else to do to cast the result to an array? I'm sure I've done this before, I have no idea why this is failing. Any help is greatly appreciated.

Edit: Here's the output when I print out
params
. As expected, it is populated with an
Array
of
Dictionary
's.

Optional([["stmtDate": cmd, "transId": identifier, "isSupplementDataAvailable": true]])

Answer

Either it's an array

if let array = parameters["inputVO"] as? [[String:Any]] { ... }

or a dictionary

if let dictionary = parameters["inputVO"] as? [String:Any] { ... }

Both types are generics and need specific type information

  • [[String:Any]] is the short form of Array<Dictionary<String,Any>>
  • [String:Any] is the short form of Dictionary<String,Any>
Comments