An empty array comes to me

[]

public func getLastestNews(_ url: String) { print("Start Download") let request = URLRequest(url: URL(string: url)!) let urlSession = URLSession.shared let task = urlSession.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if let error = error { print(error) return } //Parsing if let data = data { self.parseJSONData(data) } }) task.resume() } // MARK: - Parse Data private func parseJSONData(_ data: Data) { do { let temp: NSString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! let myNSData = temp.data(using: String.Encoding.utf8.rawValue)! let jsonResult = try JSONSerialization.jsonObject(with: myNSData, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary let jsonNews = jsonResult["posts"] as! [AnyObject] 

How to parse an empty array?

The penultimate line writes an error

Could not cast value of type '__NSArrayM' (0x108930db0) to 'NSDictionary' (0x108931288).

    3 answers 3

    There are two options:

    one)

     guard let array = jsonResult["posts"] as? [AnyObject] else { // дСйствия Ссли массив пустой } 

    2)

     if let array = jsonResult["posts"] as? [AnyObject] { // дСйствия Ссли массив Π½Π΅ пустой } else { // дСйствия Ссли массив пустой } 

    jsonResult["posts"] as! [AnyObject] jsonResult["posts"] as! [AnyObject] - So of course there will be crash, the whole point is in as! You try to implicitly unwrap , when you do this, you need to be sure that the value is not nil . Ie, you should check the value for nil before doing an implicitly unwrap .

    • Great answer. - Kerim Khasbulatov

    Thank you Vitali Eller for the answer. But here I will write the correct answer that earned me.

     guard let jsonResult = try JSONSerialization.jsonObject(with: myNSData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary else { return } guard let jsonNews = jsonResult["posts"] as? [AnyObject] else { return } 
    • That's right, you previously did force unwrap , and since the value was empty, it was crash. Try to avoid the code further ! - Vitali Eller

    If you get an empty array [] , then it falls on your line

     let jsonResult = try JSONSerialization.jsonObject(with: myNSData, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 

    Because it cannot lead and make force unwrap array in a Dictionary , which is what it says:

    Could not cast value of type '__NSArrayM' (0x108930db0) to 'NSDictionary' (0x108931288)

    You need to either handle the possible response options: If empty, then the array, if not empty, is a Dictionary? Some crutches. Or does the array have to come? Then parse it as an array.

    And try to stay away from ! better optional binding :

     if let constantName = someOptional { statements }