问题描述
我有执行 NSFetchRequest
的代码,并将其结果转换为我的自定义数据模型类型的数组。提取可能会抛出,但我不想关心错误所以我使用尝试?
,我还使用作为?
在铸造中。在Swift 2中,这曾经很好,但是Swift 3产生了一个双重选项:
I have code for executing an NSFetchRequest
and casting its result to an array of my custom data model type. Fetching may throw but I don't want to care about the error so I use try?
, and I also use as?
in casting. In Swift 2, this used to be just fine, but Swift 3 produces a double optional:
var expenses: [Expense]? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: Expense.entityName)
request.predicate = NSPredicate(format: "dateSpent >= %@ AND dateSpent <= %@", [self.startDate, self.endDate])
// Returns [Expense]? because right side is [Expense]??
if let expenses = try? App.mainQueueContext.fetch(request) as? [Expense],
expenses?.isEmpty == false {
return expenses
}
return nil
}
如果允许,我如何在中重新定义可选绑定的右侧,以便其类型简单是一个数组
[费用]
?我认为在下面的布尔条件(曾经是 where
子句)中看起来很荒谬,数组仍然是可选的。
How can I rephrase the right side of my optional binding in if let
so that its type will simply be an array [Expense]
? I think it looks absurd that in the following boolean condition (which used to be a where
clause), the array is still optional.
推荐答案
你必须在括号内包装 try?
,如下所示:
You must wrap your try?
call within parenthesis like this :
if let expenses = (try? App.mainQueueContext.fetch(request)) as? [Expense]
那是因为为?
有优先级高于尝试?
(可能是因为 try?
可以应用于整个表达式。)
That's because as?
has a higher precedence than try?
(probably because try?
can be applied to the whole expression).
这篇关于可选绑定试试?并作为?仍然会生成一个可选类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!