Jeppe Christensen Jeppe Christensen - 1 month ago 12
Swift Question

Cannot instantiate function Could not cast value of type '__NSArrayI'

I have made the following function in Swift 3:

func parseJSON() {
var JsonResult: NSMutableArray = NSMutableArray()

do {
JsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement:NSDictionary=NSDictionary()
let locations: NSMutableArray = NSMutableArray()

for i in 0 ..< JsonResult.count
{
jsonElement = JsonResult[i] as! NSDictionary
let location = Parsexml()

if let title = jsonElement["Title"] as? String,
let body = jsonElement["Body"] as? String,
let userId = jsonElement["UserId"] as? Int,
let Id = jsonElement["Id"] as? Int
{

location.title = title
location.body = body
location.userId = userId
location.id = Id

}

locations.add(location)
}
DispatchQueue.main.async { () -> Void in

self.delegate.itemsDownloaded(items: locations)

}


When i call this function from another method, i get the following error:


Could not cast value of type '__NSArrayI' (0x105d4fc08) to 'NSMutableArray' (0x105d4fcd0).


It points me towards the element here:

JsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSMutableArray


Where it exits with a SIGBRT..

What have i missed here?

Answer

You are trying to convert an NSArray into an NSMutable array which is what the warning is complaining about.

Take the array it provides you, and then convert it into a mutable one.

let jsonArray = try JSONSerialization.jsonObject(with: self.data as Data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
jsonResult = jsonArray.mutableCopy() as! NSMutableArray

Unrelated, but you may also want to user a lower case value for the JsonResult to fit with normal iOS style guidelines. It should instead be jsonResult.

Comments