ios - Call function that throws and attempt to cast the returned value, abort silently if either fails -


i'm guarding call method may throw (a coredata fetch request), , @ same time i'm casting returned value specific type of array:

guard let results = try? managedcontext.executefetchrequest(fetchrequest) as? [mymanagedobjectclass] else {      // bail out if fetch or cast fails:     return } 

the way understand that, because i'm using guard/try?/else (instead of do/try/catch), else block (i.e. return statement) above executed if either of following occurs:

  1. the fetch request fails (and throws)
  2. the fetch request succeeds casting of returned value [mymanagedobjectclass] fails.

the code above works, after control passes guard check, variable results ends being of type [mymanagedobjectclass]? ("optional array of mymanagedobjectclass").

so if want -say- loop through array elements i have first unwrap it:

if let results = results {     // now, 'results' of type:     // "(non-optional) array of mymanagedobjectclass"       element in results {         // (process each element...)     } } 

i could use as! instead of as? when casting after guard statement; makes results non-optional array.

but then, if fetch succeeds cast fails, still trigger runtime error (crash) instead of control flowing else block, right?.

is there smarter way? (catch both errors, end non-optional array)


note: understand lumping both failure causes (fetch , cast) 1 else block not best design, , perhaps should check both separately (perhaps should use more traditional do/try/catch), better grasp details of complex construct.

you need wrap try call parentheses:

let results = (try? managedcontext.executefetchrequest(fetchrequest)) as? [mymanagedobjectclass] 

otherwise try? apply whole expression, generating optional value gets assigned results.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -