Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnyObject to Array?

I'm using NSJSONSerialization as so:

let twData: AnyObject? = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: &dataError) 

This gives me an AnyObject?.

From here, I want to convert it to Array<Dictionary<String,String>>

I've tried all sorts, leading up to this:

var twDataArray: Array<Dictionary<String,String>>? = twData? as? Array<Dictionary<String,String>> 

which simply gives the error:

Type 'Array>' does not conform to protocol 'AnyObject'.

And putting the simpler version:

var twDataArray = twData as Array 

gives the error:

Cannot convert the expression's type 'AnyObject?' to type 'Array'

like image 468
Andrew Avatar asked Sep 29 '14 10:09

Andrew


Video Answer


2 Answers

To cast your data to an array:

var twDataArray = (twData as! NSArray) as Array 

The code above first casts twData to an NSArray, and then to an Array via a bridging cast. A bridging cast is a special type of cast which converts an Objective-C type to it's _ObjectiveCBridgeable conformant, Swift counterpart.

(Note that I didn't need to write Array<AnyObject> because the element AnyObject is inferred in the bridging cast from NSArrayArray)

Note that the cast above is a forced downcast. Only use this if you're absolutely sure that twData is going to be an instance of NSArray. Otherwise, use an optional cast.

var twDataArray = (twData as? NSArray) as Array? 
like image 51
Vatsal Manot Avatar answered Sep 28 '22 09:09

Vatsal Manot


Try the following, you can iterate through the array as given below.

for element in twData as! Array<AnyObject> {     print(element) } 
like image 42
arango_86 Avatar answered Sep 28 '22 07:09

arango_86