我找了这篇文章,但它没有涵盖我的情况。
如果我理解正确,我们可以try 在 do..catch.. 语句或可以抛出的函数中使用。
但有时我会看到类似的东西:
let jsonData = try jsonEncoder.encode(employee1)
Run Code Online (Sandbox Code Playgroud)
其中 jsonData 不是可选的。这是什么意思?如果尝试语句失败怎么办?为什么值不是可选的?有人可以解释一下吗?谢谢。
除了您提到的情况外,您还可以调用try顶级代码。这是一个简单的自包含示例:
// main.swift:
enum MyError : Error {
case failed
}
func foo() throws -> Int {
throw MyError.failed
}
defer { print("Good bye.") }
let x = try foo()
print(x)
Run Code Online (Sandbox Code Playgroud)
您可以将其作为 Xcode“命令行项目”或直接从命令行编译和运行:
$ swiftc main.swift $ ./主要 再见。 致命错误:在顶层引发错误:main.MyError.failed: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/ErrorType .swift,第 187 行 非法指令:4
try顶级代码中的失败导致程序以错误消息终止。但是,将执行延迟语句(如果存在)。
这与使用强制try!语句略有不同,强制语句也会导致程序中止,但会立即中止,而不执行延迟语句。(如果延迟语句用于清理资源,例如删除临时文件,这可能是相关的)。
错误消息来自ErrorType.swift,第 187 行:
/// Invoked by the compiler when code at top level throws an uncaught error.
@_inlineable // FIXME(sil-serialize-all)
@_silgen_name("swift_errorInMain")
public func _errorInMain(_ error: Error) {
fatalError("Error raised at top level: \(String(reflecting: error))")
}
Run Code Online (Sandbox Code Playgroud)
(也在Swift 中处理类函数内的错误时的非详尽列表中观察到)。
显然,顶级代码的行为就像嵌入在 do-catch 块中一样:
do {
func foo() throws -> Int {
throw NSError(domain: "foo", code: 0, userInfo: nil)
}
defer { print("Good bye.") }
let x = try foo()
} catch {
fatalError("Error raised at top level: \(String(reflecting: error))")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
346 次 |
| 最近记录: |