Wainage
Wainage

Reputation: 5412

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.

Upvotes: 6

Views: 2513

Answers (1)

matt
matt

Reputation: 535149

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.

Upvotes: 4

Related Questions