Swift:如果 do return try 失败,则 catch 执行

Bra*_*n A 6 return swift

我正在编写一段代码,该代码NSManagedObject将从 CoreData 中获取一个s数组。在我的代码中使用 do catch 语句时,这样做似乎不正确,但这是我编写这行代码的最简单方法。

在任何其他情况下,当您使用该return语句时,您将跳出您所在的当前函数。并且您可以放心,您的函数中的其他代码将不会执行该return语句。我想知道这是否同样适用于 Swift 的do catch范式。

class func getAll() -> [MMNotification] {
    let context = appDelegate.persistentContainer.viewContext
    let fetchRequest = NSFetchRequest<MMNotification>(entityName: "MMNotification")
    do {
        return try context.fetch(fetchRequest)
    }
    catch {
        // Will this 'catch' if the try fails, 
        // even if we said we are 'return'ing right before the 'try'?
        return []
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我正在获取存储在 CoreData 中的通知列表。在do块中,您可以看到有问题的代码行。

请问catch块执行,如果try失败之后,已经说明该函数应该return

Str*_*ers 6

你所拥有的应该按预期工作。基本上发生的情况是,如果在 do 内的任何时间发生 throw ,则调用 catch 并且不会执行 throw 之后的任何代码。