本文介绍了与 try 的可选绑定?并作为?仍然产生一个可选类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于执行 NSFetchRequest 并将其结果转换为我的自定义数据模型类型数组的代码.获取可能会抛出,但我不想关心错误,所以我使用 try?,并且我也在转换中使用 as?.在 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
}

如何在 if let 中改写可选绑定的右侧,使其类型只是一个数组 [Expense]?我认为在以下布尔条件(曾经是 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]

那是因为 as? 的优先级高于 try?(可能是因为 try? 可以应用于整个表达式).

That's because as? has a higher precedence than try? (probably because try? can be applied to the whole expression).

这篇关于与 try 的可选绑定?并作为?仍然产生一个可选类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:46