本小节围绕 try?
的用法和相关知识点展开来讲,内容不多,比较简单。
示意Demo如下
// parse方法是一个可以throw error的方法。
if let result = try? parse(text: input)
{
print(result)
}
你对你的错误信息并不在意
的时候可以使用try? (swift 并不建议你去忽略错误,不过有些场景去使用try?, 真香~)
Demo如下,只做了解即可。
extension Optional {
/// Unwraps `self` if it is non-`nil`.
/// Throws the given error if `self` is `nil`.
func or(error: Error) throws -> Wrapped {
switch self {
case let x?: return x
case nil: throw error
}
}
}
do {
let int = try Int("42").or(error: ReadIntError.couldNotRead)
} catch {
print(error)
}
try!
: "我写的代码肯定没有问题
,如果有,你尽管崩溃
" 这个肯定不建议使用啊
.
我也一直觉得我写的代码不可能有问题的,可是该崩的时候还是崩。。
try?
: 上面已讲,略略略。。
try
: 常规的异常处理 配合 do catch
一起使用。