![](/img/trans.png)
[英]'[AnyObject]?' is not convertible to 'NSArray'(xcode,swift)
[英]Swift: 'NSArray?' is not convertible to 'NSArray?'
我目前正在使用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
}
确保您也保持间隔不变。
为了完整jsonResult
,这是我设置jsonResult
。 jsonResult本身是否为可选的问题与您的错误消息无关。
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.