Imbru Imbru - 1 year ago 1354
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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download