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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With