Swift try with question mark Swift try with question mark swift swift

Swift try with question mark


If you mark a try with a question mark as try?, the return value of the throwable function will be optional. It will be nil in case the function threw an error (so Swift returns a nil instead of throwing the error, hence you don't need a do-catch block) or it will be the wrapped return value of the function in case no error was thrown.

This is how you can mimic the behaviour in your own function:

func parse(values: NSMutableDicationary)->Data?{    do {        return try JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions())    } catch {        return nil    }}

This is essentially the same as:

func parse(values: NSMutableDicationary)->Data?{    return try? JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions())}


From apple documentation, try? handles an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil.

So the result is one of two:

A. there is error thrown and data is nil, and trying to use the data variable is what causing the crash

B. the thrown error is not catched by try? which happens a lot in functions that run async for some reason


try?

It returns an optional that unwraps successful values, and catches error by returning nil. Use try? when you’re try to discover only with true and false

Using try? you can't except why(reason) this gonna failed.

func parse(values: NSMutableDicationary) {    //It return only exacat value Data or nil.    if let data = try? JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions()) {        //Perform operation with data    }}