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 ())
}

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 4166 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.