Wainage Wainage - 1 year ago 77
Swift Question

Swift 3 try to default value

I'm learning Swift and I'm testing the following code

var value: String;
do {
value = try getValue()
} catch {
value = "Default Value"

which can be shortened to

let value = (try? getValue()) ?? "Default Value"

It works but I feel I may be missing a more obvious solution.

Answer Source

Your solution is just great, and extremely elegant.

I presume we would like to avoid saying var in the first line and initializing the variable later. In general, the way to initialize a value immediately with a complex initializer is to use a define-and-call construct:

let value: String = {
    do {
        return try getValue()
    } catch {
        return "Default Value"

And you would probably want to do that if the catch block was returning error information that you wanted to capture.

However, in this case, where you are disregarding the nature of the error, your expression is much more compact, and does precisely what you want done. try? will return an Optional, which will either be unwrapped if we succeed, or, if we fail, will return nil and cause the alternate value ("Default Value") to be used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download