fatal error: unexpectedly found nil while unwrapping an Optional value, Swift

fatal error: unexpectedly found nil while unwrapping an Optional value, Swift

所以我现在正在尝试将存储在 NSUserdefault 中的 NSDictionary 转换为我用于 table 内容的数组,但我遇到了很多错误,包括 "fatal error: unexpectedly found nil while unwrapping an Optional value",(当前错误) 只是想知道什么是最安全和正确的转换方式。

这是我的代码。

        let nsd:NSDictionary = NSUserDefaults.standardUserDefaults().valueForKey("storedPosts") as! NSDictionary
        for (postId, postInfo) in nsd{ //post id and the post
            let importedPost:Post = Post(postId: postId as! String, priorityLevel: postInfo.objectForKey("priorityLevel") as! String, status: postInfo.objectForKey("status") as! String, section: postInfo.objectForKey("section") as! String, userType: postInfo.objectForKey("userType") as! String, dataPosted: postInfo.objectForKey("dataPosted") as! String, lastUpdate: postInfo.objectForKey("lastUpdate") as! String, states: postInfo.objectForKey("states") as! String, personalizedToViewerData: postInfo.objectForKey("personalizedToViewerData") as! [String:Bool], content: postInfo.objectForKey("content") as! Dictionary<String, Any>)
        posts.append(importedPost)
}

如有任何建议,我们将不胜感激

当你 "force-unwrap" 一个带有 ! 的 Optional 时,你是在告诉编译器 "It's ok we can always unwrap because I know for sure there always will be a value".

但如果实际上没有任何价值,应用程序将崩溃...

所以你必须首先安全地打开你的 Optionals。

技巧有很多,目前最简单的是if let

使用 "if let" 你可以安全地将一个值解包到一个新常量中,然后你可以使用这个新常量而不是 Optional。如果你需要检查类型或向下转换,你可以使用 "conditional downcasting" (我相信真实姓名是 "optional binding")和 if let xxx = yyy as? zzz.

让我们看看如何做到这一点:

if let nsd = NSUserDefaults.standardUserDefaults().valueForKey("storedPosts") as? NSDictionary {
    // use `nsd` here
}

让我们更进一步:

if let nsd = NSUserDefaults.standardUserDefaults().valueForKey("storedPosts") as? NSDictionary {
    for (postId, postInfo) in nsd {
        if let id = postId as? String {

        }
    }
}

它有效,但我们看到对每个值使用 "if let" 会导致 "pyramid of doom"...

一个经典的解决方案是使用具有相同 "if let":

的多个可选绑定
if let nsd = NSUserDefaults.standardUserDefaults().valueForKey("storedPosts") as? NSDictionary {
    for (postId, postInfo) in nsd {
        if let id = postId as? String,
            priorityLevel = postInfo.objectForKey("priorityLevel") as? String,
            status = postInfo.objectForKey("status") as? String,
            section = postInfo.objectForKey("section") as? String {  // keep doing the same for all your values

            let importedPost = Post(postId: id, priorityLevel: priorityLevel, status: status, section: section, ...)  // etc

        }
    }
}

一个很好的副作用是您现在可以通过将 else 分支添加到需要它的 "if let" 条件来处理错误。