在Swift中的if语句中使用自定义参数处理错误

时间:2016-10-21 11:50:18

标签: ios swift error-handling swift3

我在Swift中创建了一个符合Error的自定义枚举:

enum CustomError: Error{
    case errorWith(code: Int)
    case irrelevantError
}
可以选择通过闭包从异步函数返回

CustomError,如下所示:

func possiblyReturnError(completion: (Error?) -> ()){
    completion(CustomError.errorWith(code: 100))
}

我现在想检查闭包中返回的CustomError的类型。除此之外,如果它是CustomError.errorWith(let code),则想要提取CustomError.errorWith(let code)的代码。所有这些我想使用if语句的条件来完成。与此相符:

{ (errorOrNil) in
    if let error = errorOrNil, error is CustomError, // check if it is an 
    //.errorWith(let code) and extract the code, if so
    {
        print(error)
    }
    else {
        print("The error is not a custom error with a code")
    }
} 

这是否可以使用Swift 3.0?我尝试了各种我能想到的组合,但是,所有的尝试都没有结果,最终导致编译错误。

2 个答案:

答案 0 :(得分:4)

使用ballNode?.move(toParent: _gameNode) 表达式

switch

答案 1 :(得分:1)

这样做

{ (errorOrNil) in
    if let error = errorOrNil as? CustomError, case let .errorWith(code) = error {
       print(code, error)
    } else {
       print("The error is not a custom error with a code")
    }
}

或使用switch代替if