Swift:在变量不是可选的情况下处理意外的nil值 [英] Swift: handling an unexpected nil value, when variable is not optional
问题描述
我有一个UITableViewController
通过NSFetchedResultsController
从Core Data加载其条目.像这样:
I have a UITableViewController
loading its entries from Core Data via a NSFetchedResultsController
. Like this:
let historyItem = fetchedResults.objectAtIndexPath(indexPath) as HistoryItem
historyItem
具有如下定义的title
属性:
historyItem
has a title
property defined like this:
@NSManaged var title: String
所以在cellForRowAtIndexPath
中,代码说
cell?.textLabel?.text = historyItem.title
,那应该没问题. title
不是可选的,不需要解包.
and that should all be fine. title
is not an optional and does not need unwrapping.
但是,过去,存储的Core Data已经获取了一些对象,这些对象的title
属性值为nil
.它们存储在那里,等待引起错误.如果这些对象之一显示在一个单元格中,我将在上述Swift代码行上看到运行时地址异常,该地址为0.
However, in the past, the stored Core Data has acquired some objects where the value of the title
property is nil
. They are there stored, waiting to cause errors. If one of these objects is displayed in a cell, I will see a runtime address exception on the above Swift code line, where the address is 0.
出于鲁棒性,我需要编写代码以确保传递给我的程序的存储数据不会导致崩溃.但是,我不能写
For robustness, I need to write code to make sure the stored data delivered to my program does not cause crashes. However, I cannot write
if historyItem.title == nil { } // gives compiler error
因为title
不是可选的,编译器也不允许我这样做.如果我写
because title
is not an optional and the compiler will not let me. If I write
let optionalTitle:String? = historyItem.title
我仍然在该行上获得运行时EXC_BAD_ACCESS
.
I still get a runtime EXC_BAD_ACCESS
on that line.
如何检查title
不是错误的nil?
How can I check that title
is not erroneously nil?
谢谢!
推荐答案
@NSManaged var title: String
应该为@NSManaged var title: String?
.然后,使用可选绑定就不会出错:
@NSManaged var title: String
should be @NSManaged var title: String?
if there is possibility for a nil value. Then, you cannot go wrong with optional binding:
if let historyItemTitle = historyItem.title {
cell?.textLabel?.text = historyItemTitle
} else {
cell?.textLabel?.text = "Title missing"
}
这篇关于Swift:在变量不是可选的情况下处理意外的nil值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!