Swift Nested在闭包内尝试

时间:2018-11-28 07:29:36

标签: ios swift error-handling

我有以下要求

enum CustomError1: Error {
    case errorA
}

enum CustomError2: Error {
    case errorA
}

public func func1(completion: @escaping () -> Void) throws {
    //some code
    if #somecondition {
        throw CustomError1.errorA
    }
    completion()
}

public func func2(completion: @escaping () -> Void) throws {
    //some code
    if #somecondition {
        throw CustomError2.errorA
    }
    completion()
}


func result() {
    do {
        try func1() {
            try self.func2 (){

            }
        }
    } catch {

    }
}

结果函数给出如下错误

Invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'

这是因为func1和func2提供了不同类型的错误。

由于这个原因,我需要在第一个闭包中编写另一个do catch,如下所示:

func result() {
    do {
        try func1() {
            do {
                try self.func2 (){

                }
            } catch {

            }
        }
    } catch {

    }
}

有没有一种方法可以简化这种嵌套的try catch

2 个答案:

答案 0 :(得分:3)

问题是func1的参数键入为escaping () -> Void。这意味着您不能将作为该参数传递的函数扔进去。您将需要输入escaping () throws -> Void

答案 1 :(得分:1)

enum CustomError1: Error {
    case errorA
}

enum CustomError2: Error {
    case errorA
}

public func func1(completion: @escaping () throws -> Void) throws {
    //some code
    if true {
        throw CustomError1.errorA
    }
    try completion()
}

public func func2(completion: @escaping () throws -> Void) throws {
    //some code
    if true {
        throw CustomError2.errorA
    }
    try completion()
}


func result() {
    do {
        try func1(completion: {
            try func2 (completion: {

            })
        })
    } catch {

    }
}

我不建议在带有完成的情况下使用throw。更好的方法是使用更好的完成实现。像这样:

public func func1(completion: @escaping (Error?) throws -> Void) throws {
    //some code
    if true {
        completion(CustomError1.errorA)
    }
   completion(nil)
}