Swift NSUrl exc_错误指令?

Swift NSUrl exc_错误指令?,swift,Swift,我正试图遵循本教程,在一些小的尝试和错误运行之后,我遇到了一个我不太理解的问题。我收到这个错误(?)exc\u bad\u指令。我读到过,通常当你试图打开一个零或者零是无效的 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? { var cell:iGameTable

我正试图遵循本教程,在一些小的尝试和错误运行之后,我遇到了一个我不太理解的问题。我收到这个错误(?)exc\u bad\u指令。我读到过,通常当你试图打开一个零或者零是无效的

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

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

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

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

        var credit:String? = pfObject["author"] as? String
        if credit != nil {
            cell?.gameCreditLabel?.text = "\(credit!)"
        }

        cell?.gameImageView?.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?.gameImageView?.image = UIImage(data: imageData)

                })
            }
        }
    }

    return cell
}
请看这两行:

 var url:NSURL? = NSURL(string: urlString!)
 if var url:NSURL? = NSURL(string: urlString!) {
  • 首先,你不能两者都要;他们两人都做同样的事情 不同的方式

  • 第二,第一条线路的运行方式是危险的。删除它

  • 第三,从
    urlString中删除感叹号和类型
    声明
    NSURL?

现在,您将看到以下内容:

 if var url = NSURL(string: urlString) {
这是安全的,也是这种拆开包装的方式

编辑:只是想澄清一下:这是一件非常自欺欺人的事情:

if var urlString:String? = pfObject["url"] as? String
原因如下。如果变量=
如果让=构造展开等号右侧的可选项。这就是它的目的:安全地打开可选的。但是,通过添加
:String?
声明,您可以将其重新包装为可选的格式,从而破坏了此构造的全部用途!你想说:

if var urlString = pfObject["url"] as? String

现在,
urlString
,如果它是任何东西的话,就是一个未包装的字符串,这就是您所追求的。

我可能会用let替换var,因为它是一个常量:]当然我同意,但作为一名教师,我现在正在帮助他克服这一困难。真的非常感谢您。你解释得很好。我完全忽略了他们做了同样的事情。就其他方面而言,除了从
urlString中删除感叹号外,它还能工作创建了一个错误,但我留下了它,它现在可以工作了。非常感谢。您也可以将matts答案应用于urlString以去除感叹号。无感叹号!将
字符串?
urlString
的声明中移除。那是你的错误。我的答案是正确的,但你需要在更多的地方使用它!