简体   繁体   English

致命错误:在展开可选值Swift时意外发现nil

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

So i'm now trying to convert a NSDictionary stored in NSUserdefault to my array used for table contents, but i meet many many errors including "fatal error: unexpectedly found nil while unwrapping an Optional value", (The currently one) Just wondering what's the most safe and correct way of converting it. 因此,我现在尝试将存储在NSUserdefault中的NSDictionary转换为用于表内容的数组,但是我遇到了许多错误,包括“致命错误:在展开可选值时意外发现nil”,(当前存在)只是想知道是什么最安全,正确的转换方式。

And here is my codes. 这是我的代码。

        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)
}

Any sugguestions would be appreciated 任何建议,将不胜感激

When you "force-unwrap" an Optional with ! 当您“强制打开”带有的可选项时! , you're telling the compiler "It's ok we can always unwrap because I know for sure there always will be a value". ,您是在告诉编译器“没关系,我们可以随时解包,因为我确定总会有一个值”。

But if there's actually no value, the app will crash... 但是,如果实际上没有任何价值,该应用将崩溃……

So you have to first safely unwrap your Optionals. 因此,您必须首先安全地打开Optionals。

There's a lot of techniques, the simplest for now is if let . 有很多技术,目前最简单的方法是if let

With "if let" you safely unwrap a value into a new constant, then you can use this new constant instead of the Optional. 使用“ if let”,您可以安全地将值解包为新常数,然后可以使用此新常数而不是Optional。 If you need to check the type or downcast, you can use "conditional downcasting" (the real name is "optional binding", I believe) with if let xxx = yyy as? zzz 如果您需要检查类型或向下转换,则可以使用“条件向下转换”(我相信,真实名称为“可选绑定”)以及if let xxx = yyy as? zzz if let xxx = yyy as? zzz . if let xxx = yyy as? zzz

Let's see how we could do that: 让我们看看如何做到这一点:

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

Let's go further: 让我们进一步:

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

        }
    }
}

It works, but we see that using an "if let" for every value would lead to a "pyramid of doom"... 它有效,但是我们看到对每个值使用“ if let”会导致“厄运金字塔”。

A classic solution for this is to use multiple optional bindings with the same "if let": 一个典型的解决方案是对相同的“ 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

        }
    }
}

A nice side-effect is that you can now handle errors by adding an else branch to the "if let" conditions that need it. 一个不错的副作用是,您现在可以通过在需要它的“ if let”条件中添加else分支来处理错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JSON致命错误:展开可选值时意外发现nil - JSON fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:在展开Optional值时意外发现nil,获取json错误swift - fatal error: unexpectedly found nil while unwrapping an Optional value, Get json error swift 使用JSON的Swift上的“致命错误:在展开可选值时意外发现nil” - “Fatal error: Unexpectedly found nil while unwrapping an Optional value” on Swift with JSON 解析 JSON 数据 Swift “线程 4:致命错误:在展开可选值时意外发现 nil” - Parsing JSON Data Swift “Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value” 使用Alamofire的Swift JSON-在展开可选值时意外发现nil - Swift JSON with Alamofire - Unexpectedly found nil while unwrapping an Optional value 展开Optional值JSON swift时意外发现nil - Unexpectedly found nil while unwrapping an Optional value JSON swift JSON解析并接收到:致命错误:在展开可选值时意外发现nil - JSON Parsing and recieved : fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:使用字典为有效JSON展开可选值时意外发现nil - fatal error: unexpectedly found nil while unwrapping an Optional value using Dictionary for valid JSON 如何解决此“致命错误:在解开可选值时意外发现 nil”? - How can I fix this "Fatal Error: unexpectedly found nil while unwrapping optional value"?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM