Error handling 快2接球!失败错误

Error handling 快2接球!失败错误,error-handling,swift2,Error Handling,Swift2,有时,如果我们使用as!转换错误类型为的对象将导致运行时错误。 swift2介绍了try-catch-throw错误处理方式。 那么,有没有一种方法来处理as!使用新的try-catch方式出现失败运行时错误,do-try-catch语句仅用于处理抛出函数。如果要处理强制转换,请使用as?: if let x = value as? X { // use x } else { // value is not of type X } 或者新的守卫声明 guard let x = valu

有时,如果我们使用as!转换错误类型为的对象将导致运行时错误。 swift2介绍了try-catch-throw错误处理方式。
那么,有没有一种方法来处理as!使用新的try-catch方式出现失败运行时错误,
do-try-catch
语句仅用于处理抛出函数。如果要处理强制转换,请使用
as?

if let x = value as? X {
  // use x
} else {
  // value is not of type X
}
或者新的守卫声明

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

作为!是一个允许您强制将实例强制转换为某种类型的运算符。施法并不意味着皈依。小心!如果您不确定类型,请使用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值,然后尝试作为?(如果您选择引用类型)

请查看我的答案