gpt4 book ai didi

swift - 在 Swift 中捕获异常?

转载 作者:搜寻专家 更新时间:2023-11-01 05:40:12 25 4
gpt4 key购买 nike

据我所知,如果不将 throw 集成到您的函数中,就不可能在 Swift 中捕获异常。

换句话说,以下内容不起作用,其中 myArr 只有 5 个项目:

        do {
var someItem = try myArr[10]
}
catch {
print("something went wrong")
}

谁能确认上述简单的 try/catch 在 Swift 中是不可能的?换句话说,您不必构建一些复杂的元异常函数来处理异常?

最佳答案

正确,但您还有其他选择。您可以简单地检查 10 < myArr.count首先。

或者,查看 Erica Sadun 在 Safe array indexing 上的帖子:

// Erica Sadun / Mike Ash
// http://ericasadun.com/2015/06/01/swift-safe-array-indexing-my-favorite-thing-of-the-new-week/
extension Array {
subscript (safe index: UInt) -> Element? {
return Int(index) < count ? self[Int(index)] : nil
}
}

关于swift - 在 Swift 中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31578216/

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