gpt4 book ai didi

swift - 从类型 '(NSData!, NSError!) throws -> ()' 的抛出函数到非抛出函数类型 '(NSData!, NSError!) -> Void' 的转换无效

转载 作者:行者123 更新时间:2023-11-30 13:28:30 27 4
gpt4 key购买 nike

我试图在 if let jsonData Array = try NSJSONSerialization... 行中从 Swift 1 转换为 2,因为它最初给了我一个来自“额外参数‘错误’的错误” call”所以我在 NSJSONSerialization 之前添加了“try”,但现在它说“从 '(NSData!, NSError!) throws -> ()' 类型的抛出函数到非抛出函数类型 '(NSData! , NSError!) -> Void'。我认为错误没有得到正确处理,但我不知道该怎么做。这是代码

httpHelper.sendRequest(httpRequest, completion: {(data:NSData!, error:NSError!) in
if error != nil {
let errorMessage = self.httpHelper.getErrorMessage(error)
let errorAlert = UIAlertView(title:"Error", message:errorMessage as String, delegate:nil, cancelButtonTitle:"Ok")
errorAlert.show()

return
}

var error: NSError?

// let jsonDataDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &error) as! NSDictionary
// let jsonDataDict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary

if let jsonDataArray = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as? NSArray! {
//load collection view with selfies
if jsonDataArray != nil {
for imageDataDict in jsonDataArray {
var selfieImgObj = SelfieImage()

selfieImgObj.imageTitle = imageDataDict.valueForKey("title") as! String
selfieImgObj.imageId = imageDataDict.valueForKey("random_id") as! String
selfieImgObj.imageThumbnailURL = imageDataDict.valueForKey("image_url") as! String

self.dataArray.append(selfieImgObj)
}

self.collectionView?.reloadData()
}
}
})
}

最佳答案

首先,您应该将所有调用 throws 的函数包装在 do-try-catch 循环中。其次,安全地将 jsonArray 解包为 Swift 数组,而不是尝试将其强制转换为 NSArray:

do {
if let jsonArray = try NSJSONSerialization.JSONObjectWithData(NSData(), options: .AllowFragments) as? [AnyObject] {
// unarchived data is an array
}
} catch {
print(error)
}

关于swift - 从类型 '(NSData!, NSError!) throws -> ()' 的抛出函数到非抛出函数类型 '(NSData!, NSError!) -> Void' 的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36852152/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com