swift2赶上了!失败错误

时间:2015-06-29 02:33:50

标签: error-handling swift2

有时如果我们使用as!转换具有错误类型的对象将导致运行时错误。 swift2引入了try catch throw错误句柄方式。 所以,有没有办法处理!使用新的try catch方式失败运行时错误

3 个答案:

答案 0 :(得分:9)

try catch语法仅用于处理投掷函数。如果你想处理强制转换,请使用as?

if let x = value as? X {
  // ...
}

或新的警卫声明

guard let x = value as? X else {
  // ...
}

答案 1 :(得分:1)

如!是一个允许您强制将实例强制转换为某种类型的运算符。 cast并不意味着转换。小心!如果您不确定类型,请使用? (条件转换)返回所需类型的对象或零。

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值上的对象,然后尝试? (如果你转换为引用类型)

答案 2 :(得分:0)

在Swift 2.0中,后卫会帮助你一些时间。但无论何时使用 as!,这意味着您的意图非常明确,并且您保证它应该始终具有值。 希望你明白。