gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:54:00 25 4
gpt4 key购买 nike

我在 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 吗?我尝试了各种我能想到的组合,但是,所有尝试都没有结果,并以编译时错误告终。

最佳答案

使用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")
}

关于ios - 在 Swift 的 if 语句中使用自定义参数处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40175988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com