fatal error: NSArray element failed to match the Swift Array Element type

BaSha picture BaSha · Aug 25, 2014 · Viewed 33.2k times · Source

Suddenly I'v started getting run time error as,

fatal error: NSArray element failed to match the Swift Array Element type

I'v declared my array as,

var myArray : [CUSTOM_CLASS] = [CUSTOM_CLASS]()

Now, in my server response success block I have,

self.myArray = dicResponse["data"]! as Array

println(self.myArray) // FATAL ERROR HERE

Which was working perfect before upgrading to Xcode6 Beta6

FYI : dicResponse["data"]! // is verified as valid

(Sorry to pointing wrong place before!)

SOLVED :

Dont know but I'd made some changes and it works,

var myArray = [AnyObject]()

self.myArray = dicResponse["data"]! as [AnyObject]

Answer

Max MacLeod picture Max MacLeod · Sep 11, 2014

If I could supplement Teejay's answer with some further information. This error:

fatal error: NSArray element failed to match the Swift Array Element type

is caused by a type mismatch.

For example having cast to your Swift array type:

    myPersonList = aDictionary["persons"] as [Person]

Accessing the value in aDictionary based upon key "persons", Swift expects to receive an array of type Person. This will compile and will execute without issue.

However, later in your code when accessing the myPersonList array element, if the type is not as specified - in my example Person - then execution will crash with the error above.

Bottom line: you almost certainly have specified the wrong type in the cast. Examine your dictionary object to see what it really contains.