我想测试数组的计数是否大于0,否则忽略当前视图。
现在我这样做:
do {
let pets = try self.managedObjectContext.fetch(request)
guard pets.count > 0 else {
self.dismiss(animated: true, completion: nil)
}
dateCreated = Date(timeIntervalSince1970: Double(pets[0].dateCreated))
} catch {
self.dismiss(animated: true, completion: nil)
}
我想知道如果计数不大于0,我是否可以手动将do..catch
发送到catch
,这样我就不必self.dismiss(animated: true, completion: nil)
{{1}} 1}}写了两次。有人知道这是否可行?
答案 0 :(得分:4)
显然,您并不关心error
,因此您可以使用try?
代替do-catch
:
guard
let pets = try? self.managedObjectContext.fetch(request),
!pets.isEmpty
else {
self.dismiss(animated: true, completion: nil)
return
}
dateCreated = Date(timeIntervalSince1970: Double(pets[0].dateCreated))
另一个选择是将重复的代码移动到函数/闭包中,例如
let onError: () -> Void = {
self.dismiss(animated: true, completion: nil)
}
do {
let pets = try self.managedObjectContext.fetch(request)
guard pets.count > 0 else {
onError()
return
}
dateCreated = Date(timeIntervalSince1970: Double(pets[0].dateCreated))
} catch {
onError()
}
答案 1 :(得分:1)
如果您与do
区块结合,则可以执行此操作:
struct MyError: Error { }
do {
let pets = try self.managedObjectContext.fetch(request)
guard pets.count > 0 else {
throw MyError()
}
dateCreated = Date(timeIntervalSince1970: Double(pets[0].dateCreated))
} catch {
self.dismiss(animated: true, completion: nil)
}
答案 2 :(得分:0)
听起来您想尝试使用defer
。
guard
条件未返回。这有问题。
尝试类似
的内容defer {
self.dismiss(animated:true, completion:nil)
}
do {
let pets = try self.managedObjectContext.fetch(request)
guard pets.count > 0 else {
return
}
dateCreated = Date(timeIntervalSince1970: Double(pets[0].dateCreated))
} catch {
// TODO - do any error work required if no pets. Possibly nothing.
}
使用defer
将保证在退出方法时调用代码行。