rod*_*fus 0 error-handling ios swift swift3
我创建了一个符合ErrorSwift的自定义枚举,如下所示:
enum CustomError: Error{
case errorWith(code: Int)
case irrelevantError
}
Run Code Online (Sandbox Code Playgroud)
CustomError 可以选择通过闭包从异步函数返回,如下所示:
func possiblyReturnError(completion: (Error?) -> ()){
completion(CustomError.errorWith(code: 100))
}
Run Code Online (Sandbox Code Playgroud)
我现在想检查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")
}
}
Run Code Online (Sandbox Code Playgroud)
这完全可能使用 Swift 3.0 吗?我尝试了我能想到的各种组合,但是,所有尝试都没有结果,并以编译时错误告终。
使用switch表达式
if let error = error as? CustomError {
switch error {
case .errorWith(let code):
print("error has code:" code)
case .irrelevantError:
print("irrelevantError")
}
} else if error != nil {
print("The error is not a custom error with a code")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1209 次 |
| 最近记录: |