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"
    }
}
do {
    let result = try say(words: "five")
} catch {
    print("出问题啦。。。。。")
}
// 返回值是一个可选类型,如果执行正常的话就存在返回值,否则如果抛出错误的话返回值为nil
let result = try? say(words: "four")
// 可选绑定
if let res = try? say(words: "four") {
}
// 提前退出
guard let resu = try? say(words: "four") else { return }
// 对返回值进行强制解包,如果抛出错误则程序终止
let res = try! say(words: "five")
上一篇下一篇

猜你喜欢

热点阅读