Quickly try question mark

I see the following in the code I maintain:

func parse(values: NSMutableDicationary) {
let data = try? JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions())
}

Note that this method will not be marked as throwing anything, nor will it Handling errors. The code did crash the application.

I want to figure out what to try? (Try using a question mark) means.

Google search or StackOverflowing did not return any useful information.

So, try it? What does Swift mean?

If you use a question mark as a try?, the return value of the throwable function will be optional If the function throws an error (so Swift returns a nil instead of throwing an error, so you don’t need a do-catch block) it will be nil, otherwise it will be the wrapper return value of the function in case no error is thrown

This is how you can imitate the behavior in your own function:

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

This is basically the same as the following:

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

I see the following in the code I maintain:

func parse(values: NSMutableDicationary) {
let data = try? JSONSerialization.data(withJSONObject: values, options: JSONSerialization.WritingOptions())
}

Note that this method will not be marked as throwing anything and will not handle errors. The code does crash the application.

I want to figure out what to try? (Try using a question mark) means.

Google search or StackOverflowing did not return any useful information.

So, try it? What does Swift mean?

If you use a question mark as a try?, the return value of the throwable function will be optional. If the function throws an error (so Swift returns a nil instead of throwing an error, so you don’t need a do-catch block) It will be nil, otherwise it will be the wrapped return value of the function in case no error is thrown.

This is how you can imitate the behavior in your own function:

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

This is basically Same as the following:

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

Leave a Comment

Your email address will not be published.