Imbru Imbru - 7 months ago 797
Swift Question

Could not cast value of type NSSingleObjectArray to NSMutableArray

Since iOS10, i am facing to this issue :

Could not cast value of type '__NSSingleObjectArrayI' to
'NSMutableArray' .

There is my code :

manage.POST( url, parameters: params,
constructingBodyWithBlock: { (data: AFMultipartFormData!) in
//Some stuff here
success: { (operation: NSURLSessionDataTask?, responseObject: AnyObject?) in

var array : NSMutableArray!

if AppConfig.sharedInstance().OCR == "2"{
let dictionnary = responseObject as! NSDictionary
array = dictionnary["data"]! as! NSMutableArray
//!!!!CRASH HERE!!!!!
array = responseObject as! NSMutableArray
//Some stuff after

When i look for responseObject value, i have this in my console :

Printing description of responseObject:
▿ Optional<AnyObject>
▿ Some : 1 elements
- [0] : Test

How can i extract value "Test" from responseObject ?

Many thanks


The crash happens because you assume that the object you receive is NSMutableArray, even though the object has been created outside your code.

In this case, an array that your code gets is an instance of an array optimized for handling a single element; that is why the cast is unsuccessful.

When this happens, you can make a mutable copy of the object:

array = (dictionnary["data"]! as! NSArray).mutableCopy() as! NSMutableArray


array = (responseObject as! NSArray).mutableCopy() as! NSMutableArray