1

I am very new to swift and in my code I get JSON from a certain email, the JSON data is first put into an Array in swift, however if the array is null or there is no Json Data I get this error

Could not cast value of type 'NSNull' (0x1067a5748) to 'NSArray' (0x1067a4c58).

I been trying to fix this by reading other posts such as Check if optional array is empty but it is not working. The issue comes with this code below

session.dataTask(with:request, completionHandler: {(data, response, error) in
            if error != nil {
                   print(error)
            } else {
                do {

                    let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                    if let musicJob = parsedData["music"] as! [AnyObject]?  {

    for S in musicjob {
                        if let genre = S["genre"] as? String {
                            self.genres.append(genre)
                        }
}
}

If the Json is null I get the error on this line right here

if let musicJob = parsedData["music"] as! [AnyObject]?

The musicJob counts the number of objects such as "30 values or 44 values " etc . If there is no Json then it returns nil and it crashes . Is there anyway that I can catch the value of nil or an empty array so that the app does not crash ? Again everything works as long as the musicJob array is not empty .

Community
  • 1
  • 1
user1949387
  • 1,245
  • 3
  • 21
  • 38
  • 1
    Think a moment about the meaning to forced unwrap an optional to an optional (`as! [AnyObject]?`). Apart from that an unspecified JSON type in Swift 3 is always `Any` rather than `AnyObject`. – vadian Nov 23 '16 at 05:14

3 Answers3

6

Try this:

if let musicJob = parsedData["music"] as? [AnyObject]
Bista
  • 7,869
  • 3
  • 27
  • 55
4

You can check both nil and empty for Array like this.

if let musicJob = parsedData["music"] as? [Any], !musicJob.isEmpty {
    print(musicJob)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
1

Yes. You can always use conditional unwrapping. Force unwrapping is usually dangerous (crash) and should be used with great care.

First of all, using guard to make sure preconditions are met before doing anything is a good practice.

if guard let responseData = data else {
    assertionFailure("response data is nil") // no need for assertionFailure is data is expected to be nil sometimes
    return
}

And something similar with the line that crashes:

if let musicJob = parsedData["music"] as? [AnyObject] {
    ....
}
skim
  • 2,267
  • 2
  • 16
  • 17