Allow operation for optional try

The try? statement brings great syntax simplicity to do...catch, however, the only loss is the catch part, which sometimes critical for purposes such as logging.
Proposal:

let foo: Int
do {
  foo = try bar()
} catch {
  foo = 0
  print("log \(error)")
}

can be simplified to:

let foo = try? bar() ?? 0 !! print("log \(error)")

for void or discardable returns, the try? can be simplified as:

try? foo() !! print(error)
2 Likes

Unless I'm reading it incorrectly, that proposal doesn't seem to be the same as what's being pitched in this thread (other than sharing the same spelling for the operator it wants to create).

This is an excellent idea, but or (or ||) instead of !! will feel more natural when reading.

let foo = try? bar() ?? 0 or print ("log \(error)")

try? foo() or print (error)

@Rocky_Wei I'm not a big fan of the ?? followed by !!, it's very confusing to me to read because the ! is known to be a "force unwrapping" operator and this feels like an unsafe feature. Also, all developers would need to learn the precedence (that ?? is higher than !!).

The problem you're trying to solve reminds me of the also function in Kotlin:

Applying the same idea to Swift would look somewhat like this:

let foo = try? bar() ?? 0.also { print("log \($0)") }

I'm not saying this is "better" or anything, just another approach to consider. And I believe you could just add this global function to your app and use it right now without any changes to the language (source):

@inline(__always) func also(block: (Self) -> ()) -> Self {         
    block(self)
    return self
}