gpt4 book ai didi

swift - 是否可以使用 "try?"在保护语句中检索异常?

转载 作者:IT王子 更新时间:2023-10-29 05:37:10 25 4
gpt4 key购买 nike

在 swift 中,是否可以使用更短的 guard let try? 在进入 else block 时获取发生的异常?

guard let smth = try? myThrowingFunc() else {
print(error) //can I access the exception here somehow?
return
}

对比

let smth: AnyObject?
do {
smth = try myThrowingFunc()
} catch let error {
print(error)
return
}

最佳答案

我在“The Swift Programming Language (Swift 2.2 Prerelease)”中找到第 42 页,其中明确说明了以下内容:

Another way to handle errors is to use try? to convert the result to an optional. If the function throws an error, the specific error is discarded and the result is nil. Otherwise, the result is an optional containing the value that the function returned.

所以,这更像是对 apple 的功能请求。事实上,这里已经有一些关于这个话题的讨论:

http://thread.gmane.org/gmane.comp.lang.swift.evolution/8266

关于swift - 是否可以使用 "try?"在保护语句中检索异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35776383/

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