有时如果我们使用as!转换具有错误类型的对象将导致运行时错误。swift2介绍了try catch抛出错误的处理方式。那么,有没有办法来处理as!使用新的try catch方法时出现失败运行时错误
发布于 2015-06-29 17:09:07
do try catch语句仅用于处理抛出函数。如果想要处理类型转换,请使用as?
if let x = value as? X {
// use x
} else {
// value is not of type X
}或者是新的guard语句
guard let x = value as? X else {
// value is not of type X
// you have to use return, break or continue in this else-block
}
// use x发布于 2015-12-16 20:58:44
就像!是一个运算符,它允许您强制将实例强制转换为某种类型。cast并不意味着转换。注意!如果您不确定类型,请使用as?(条件类型转换),它返回所需类型的对象或nil。
import Darwin
class C {}
var c: C! = nil
// the conditional cast from C! to C will always succeeds, but the execution will fail,
// with fatal error: unexpectedly found nil while unwrapping an Optional value
if let d = c as? C {}
// the same, with fatal error
guard let e = c as? C else { exit(1)}即使强制转换将成功,您的对象也可以具有空值。因此,首先检查对象的nil值,然后尝试为?(如果强制转换为引用类型)
https://stackoverflow.com/questions/31106954
复制相似问题