简体   繁体   中英

Swift: 'NSArray?' is not convertible to 'NSArray?'

I'm currently developing my first iOS app with Swift 2.0. I'm getting the following error:

'NSArray?' is not convertible to 'NSArray?'

At this line:

if let results: NSArray = jsonResult["results"] as? NSArray{

Full code snippet:

do{
   let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

   if let results: NSArray = jsonResult["results"] as? NSArray{
      dispatch_async(dispatch_get_main_queue(), {
         self.tableData = results
         self.appsTableView!.reloadData()
      })
   }
}catch let error as NSError{
   print(error)
}

Can someone tell me what I'm doing wrong here?

EDIT:

My complete function: http://i.imgur.com/fCS73LF.png

You are confusing the compiler with too many (superfluous) type annotations.

// tested in Playground
if let results = jsonResult["results"] as? NSArray {
  // do something with results
}

Make sure you keep the spacing intact as well.

For completeness, here is how I set up jsonResult . The question if jsonResult itself is an optional or not has nothing to do with your error message.

let jsonResult = NSDictionary(dictionary: ["results" : [1,2,3,4,5]])

EDIT: Swift 2 version with try catch syntax

var originalDictionary = NSDictionary(dictionary: ["results" : [1,2,3,4,5]])
do {
    let data = try NSJSONSerialization.dataWithJSONObject(originalDictionary, options: NSJSONWritingOptions())
    let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? NSDictionary
    if let results = jsonResult!["results"] as? NSArray {
        for x in (results as! [Int]) {
            print("\(x)")
        }
    }
}
catch let error as NSError {
    print(error.description)
}
catch {
    print("no clue what went wrong")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM