Swift可选类型未展开

时间:2015-10-27 15:33:10

标签: ios swift

我可能因为Swift的新版本而遇到了问题。问题是这行代码不断产生错误说:

  

“可选类型的值'()?'没打开;你的意思是用'!'还是'?'?

cell?.hypeImageView?.image = UIImage(data: imageData)

这是整个功能:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {

    var cell:HypeTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? HypeTableViewCell
    if(cell == nil) {
        cell = NSBundle.mainBundle().loadNibNamed("HypeTableViewCell", owner: self, options: nil)[0] as? HypeTableViewCell
    }

    if let pfObject = object {
        cell?.hypeNameLabel?.text = pfObject["name"] as? String

        var votes:Int? = pfObject["votes"] as? Int
        if votes == nil {
            votes = 0
        }
        cell?.hypeVotesLabel?.text = "\(votes!) votes"

        let credit:String? = pfObject["cc_by"] as? String //if prob change to var
        if credit != nil {
            cell?.hypeCreditLabel?.text = "\(credit!) / CC 2.0"
        }

        cell?.hypeImageView?.image = nil
        if var urlString:String? = pfObject["url"] as? String {
            var url:NSURL? = NSURL(string: urlString!)
            if var url:NSURL? = NSURL(string: urlString!) {
                var error:NSError?
                var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)

                NSOperationQueue.mainQueue().cancelAllOperations()

                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
                    (response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in

                    cell?.hypeImageView?.image = UIImage(data: imageData)

                })
            }
        }

    }

    return cell

}

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

假设您正在使用Swift 2.0更改completionHandler的签名以期望选项而不是隐式解包选项,那么问题就会消失。

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in

    guard let imageData = data else {
        assertionFailure("No data found")
        return
    }

    cell?.hypeImageView?.image = UIImage(data: imageData)
}