我试图将if let jsonData Array = try NSJSONSerialization...行中的Swift 1转换为2,因为它最初给我“调用中的额外参数'error'带来的错误”,所以我在NSJSONSerialization之前添加了“ try”,但现在它的意思是“ Invalid从'(NSData!, NSError!) throws -> ()' to non-throwing function type '(NSData!, NSError!) -> Void'类型的throwing函数进行转换。我认为该错误未得到正确处理,但我不知道该怎么做。这是代码

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!),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36852152/

10-14 23:25