【发布时间】:2017-03-03 17:25:47
【问题描述】:
我在 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 吗?我尝试了我能想到的各种组合,但是,所有尝试都没有结果,并以编译时错误告终。
【问题讨论】:
-
你想在哪里比较错误代码?您的意思是,通过检查错误代码,您想返回一些自定义错误消息?
-
差不多就是这样。对于
CustomError.errorWith(let code)这两种情况和任何其他错误,我想以不同的方式处理错误。 @金刚狼
标签: ios swift error-handling swift3