【问题标题】:Swift Optional Type not UnwrappedSwift 可选类型未解包
【发布时间】:2015-10-27 15:33:09
【问题描述】:

我遇到问题可能是由于 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

}

我该如何解决这个问题?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    假设您使用的是 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多