小编esc*_*ian的帖子

将错误绑定到变量的 Swift Catch 模式

使用 Swift 4.2 和 XCode 10

在 Swift 4.2 中, DecodingError 是一个枚举。(目前)有四种不同的情况。我可以分别捕获每种情况,并绑定可用于记录错误的变量,如下面的代码所示...

do {
    let model = try jsonDecoder.decode(BattleShip.self, from: jsonData!)
    print(model)
} catch DecodingError.dataCorrupted(let context) {
    print(context.debugDescription)
} catch DecodingError.keyNotFound(let key, let context) {
    print("\(key.stringValue) was not found, \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
    print("\(type) was expected, \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
    print("no value was found for \(type), \(context.debugDescription)")
} catch {
    print("I know not this error")
}
Run Code Online (Sandbox Code Playgroud)

但这是很多代码,可以放在我可能遇到解码错误的任何地方。而且,如果我的 do{} 块有多个抛出的调用,我可能需要处理这些方法调用不同的错误。我试图实现的模式看起来像这样......其中decodeError(error) 包含上面所有的凌乱代码

do { …
Run Code Online (Sandbox Code Playgroud)

catch-block xcode10 swift4.2

6
推荐指数
1
解决办法
2368
查看次数

标签 统计

catch-block ×1

swift4.2 ×1

xcode10 ×1