Search code examples
swiftdo-catch

Manually go to catch statement of do...catch


I want to test if an array's count is greater than 0, otherwise dismiss the current view.

Right now I'm doing it like this:

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)
}

I'm wondering if I can just manually send the do..catch into the catch if the count is not greater than 0, that way I don't have to have self.dismiss(animated: true, completion: nil) written twice. Does anybody know if this is possible?


Solution

  • Obviously you don't care about the error therefore you can use try? instead of 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))
    

    Another option is to move the duplicated code into a function/closure, e.g.

    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()
    }