手动去抓住做...抓住的声明

时间:2017-04-19 16:01:01

标签: swift do-catch

我想测试数组的计数是否大于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}}写了两次。有人知道这是否可行?

3 个答案:

答案 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将保证在退出方法时调用代码行。