斯威夫特:“ NSArray?” 不能转换为“ NSArray?”

Kaanmijo

我目前正在使用Swift 2.0开发我的第一个iOS应用。我收到以下错误:

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

在这一行:

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

完整代码段:

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)
}

有人可以告诉我我在做什么错吗?

编辑:

我完整的功能:http : //i.imgur.com/fCS73LF.png

蒙迪

您将编译器与太多(多余的)类型注释混淆了。

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

确保您也保持间隔不变。

为了完整起见,这是我的设置方法jsonResultjsonResult本身是否是可选的问题与您的错误消息无关。

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

编辑:具有尝试捕获语法的Swift 2版本

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")
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章