检索可选值 swift

retrieve an optional value swift

我有这个功能:

func richiamoImmagine()
{
    let avatarFile = PFUser.currentUser()!["Avatar"] as! PFFile
    avatarFile.getDataInBackgroundWithBlock {
        (imageData:NSData?, error:NSError?) -> Void in
        if error == nil {
            if let finalimage = UIImage(data: imageData!) {
                self.avatarImage.image = finalimage
            }
        }
    }
}

从解析中检索图像,但如果用户没有任何图像,该函数会导致崩溃,并且此错误会出现在日志中:

fatal error: unexpectedly found nil while unwrapping an Optional value

我知道我必须放这样的东西:

if let "variable" == avatarFile 

因此,如果该函数没有检索到任何内容,至少它不会使我的应用程序崩溃!我该如何解决这个错误?

大概发生崩溃的地方在这一行:

if let finalimage = UIImage(data: imageData!) {

因为您使用的是强制解包运算符。我会在前面的 if 语句中添加一个快速检查以检查是否为 not nil:

if error == nil && imageData != nil {

甚至更好地使用 可选绑定:

if let imageData = imageData where error == nil {
    if let finalimage = UIImage(data: imageData) {
        self.avatarImage.image = finalimage
    }
}

更新:如果错误发生在第一行,那么您应该(再次)使用可选绑定来防止意外崩溃:

if let avatarFile = PFUser.currentUser()?["Avatar"] as? PFFile {

}