gpt4 book ai didi

swift - 从 Swift 异常生成错误表

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

我想从 Swift 异常处理程序生成 NSAlert 样式的错误表。在过去使用 Objective-C 我可以简单地使用 [NSAlert alertWithError:] 现在使用 Swift 并且它自己的异常处理系统混合在一起,警报感觉相当笨拙:

enum Problems: ErrorType {
case Bad
case Worse
}

func f() throws {
throw Problems.Worse
}

func g() {
let errorMessage: String

do {
try f()
}
catch Problems.Bad {
errorMessage = "This was bad"
}
catch Problems.Worse {
errorMessage = "This was even worse"
}
catch {
errorMessage = "This was unexpected"
}

guard errorMessage == nil else {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = errorMessage
alert.beginSheetModalForWindow(self, completionHandler: { [unowned self] (returnCode) -> Void in
if returnCode == NSAlertFirstButtonReturn {
// Handle the response
}
})
}

如果有许多必须检查的错误条件,这感觉很笨拙,并且无法很好地扩展。有没有更好的办法?

最佳答案

Swift 允许您的 ErrorType 具有关联数据。这或多或少是 NSErroruserInfo 的分解版本。如果你想要方便,你可以写一个函数来将 Problems 枚举转换为 NSError:

enum Problems: ErrorType {
case Small
case Bad(message: String?)
case Worse(message: String?)

func toNSError() -> NSError {
var errorMessage = ""

switch self {
case .Small:
errorMessage = "Small error"
case let .Bad(msg):
errorMessage = msg ?? "Default bad message"
case let .Worse(msg):
errorMessage = msg ?? "Default worse message"
}

return NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: errorMessage])
}
}

func f() throws {
throw Problems.Worse(message: nil)
}


do {
try f()
} catch let error as Problems {
let err = error.toNSError()
// now display NSAlert with err...
}

您可以使用 message: nil 抛出错误以获取默认消息,或者根据本地条件添加您自己的自定义消息:

throw Problems.Bad(message: "I have a bad feeling about this")

关于swift - 从 Swift 异常生成错误表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244684/

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