try、try?、try!的使用方法
2021-09-13 本文已影响0人
EngineerPan
enum NormalError: Error {
case one
case two
case three
case four
}
func say(words: String) throws -> String {
switch words {
case "one":
throw NormalError.one
case "two":
throw NormalError.one
case "three":
throw NormalError.one
case "four":
throw NormalError.one
default:
return "ok"
}
}
- try 的用法
必须有捕获异常后的 catch 处理语句
do {
let result = try say(words: "five")
} catch {
print("出问题啦。。。。。")
}
- try?的用法
不需要捕获异常后的 catch 处理语句
// 返回值是一个可选类型,如果执行正常的话就存在返回值,否则如果抛出错误的话返回值为nil
let result = try? say(words: "four")
// 可选绑定
if let res = try? say(words: "four") {
}
// 提前退出
guard let resu = try? say(words: "four") else { return }
- try!的用法
不需要捕获异常后的 catch 处理语句
// 对返回值进行强制解包,如果抛出错误则程序终止
let res = try! say(words: "five")