Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift2 catch as! fail error

sometimes if we use as! to convert object with error type will cause runtime error. swift2 introduce try catch throw error handle way. so,Is there a way to handle as! fail runtime error with the new try catch way

like image 675
吴浩麟 Avatar asked Jun 29 '15 02:06

吴浩麟


2 Answers

The do try catch statement is only for handling throwing functions. If you want to handle casts use as?:

if let x = value as? X {
  // use x
} else {
  // value is not of type X
}

or the new guard statement

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
like image 138
Qbyte Avatar answered Oct 02 '22 13:10

Qbyte


as! is an operator which allow you to force cast an instance to some type. cast doesn't means convert. be careful! if you are not sure about the type, use as? (conditional cast) which return you object of required type or 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)}

even though the cast will succeed, you object can have nil value. so, check the object on nil value first and than try as? (if you cast to reference type)

like image 40
user3441734 Avatar answered Oct 02 '22 13:10

user3441734