在Swift 3之前我使用的是:
guard let data = Data(contentsOf: url) else {
print("There was an error!)
return
}
Run Code Online (Sandbox Code Playgroud)
但是我现在必须使用do
,try
和catch
.我不熟悉这种语法.我该如何复制这种行为?
aya*_*aio 107
这里的区别是Data(contentsOf: url)
不再返回Optional,它会抛出.
所以你可以在Do-Catch中使用它,但没有guard
:
do {
let data = try Data(contentsOf: url)
// do something with data
// if the call fails, the catch block is executed
} catch {
print(error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)
请注意,您仍然可以使用guard
带有try?
代替try
,但随后可能出现的错误信息被忽略.在这种情况下,您不需要Do-Catch块:
guard let data = try? Data(contentsOf: url) else {
print("There was an error!")
// return or break
}
// do something with data
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
44049 次 |
最近记录: |