Swift-错误:解开可选值时意外发现nil [英] Swift - Error: unexpectedly found nil while unwrapping an optional value
问题描述
我一直在使用Swift制作应用程序,但是我在TableViewController类中始终遇到错误.我找不到任何方法来解决此问题,并不断出现此错误:
I have been making an app in Swift but I keep getting an error in my TableViewController class. I could not find any way to fix this and kept getting this error :
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell : TextTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath : indexPath!) as TextTableViewCell
let madan : PFObject = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject
cell.timestampLabel.alpha = 0
cell.usernameLabel.alpha = 0
cell.madanTextView.alpha = 0
cell.madanTextView.text = madan.objectForKey("content") as String
var dateFormatter : NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
cell.timestampLabel.text = dateFormatter.stringFromDate(madan.createdAt)
var findSender : PFQuery = PFUser.query()
findSender.whereKey("objectId", equalTo: madan.objectForKey("sender").objectId)
var i = 1
findSender.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if !error {
let user : PFUser = (objects as NSArray).lastObject as PFUser // Error here
cell.usernameLabel.text = user.username
UIView.animateWithDuration(0.5, animations: {
cell.timestampLabel.alpha = 1
cell.usernameLabel.alpha = 1
cell.madanTextView.alpha = 1
})
}
}
return cell
}
我找不到任何解决方法.
I cannot find any way to fix this.
推荐答案
看起来objects
好像又回到了nil
.首先检查是否为零:
It looks as if objects
is coming back as nil
. First check for nil:
if !error {
if let actualObjects = objects {
let possibleUser = (actualObjects as NSArray).lastObject as? PFUser
if let user = possibleUser {
cell.usernameLabel.text = user.username
// ...
}
}
}
注意:我将您的as
更改为as?
. lastObject
已经返回了Optional,因此如果最后一个对象无法转换为PFUser,则最好继续执行.另外,由于lastObject
可能返回nil,因此您还需要检查nil
.
Note: I changed your as
to as?
. lastObject
is already returning an Optional and so you might as well let the execution continue if the last object cannot be converted to PFUser. Also, because lastObject
might return nil, you also need to check that for nil
.
这篇关于Swift-错误:解开可选值时意外发现nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!