-1

我想测试一个数组的计数是否大于 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..catchcatch,这样我就不必self.dismiss(animated: true, completion: nil)写两次了。有人知道这是否可能吗?

4

3 回答 3

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()
}
于 2017-04-19T16:07:17.023 回答
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)
}
于 2017-04-19T16:11:18.727 回答
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将保证在方法退出时调用该行代码。

于 2017-04-19T16:12:33.607 回答