[swift-evolution] [Pre-Draft] Nil-coalescing and errors

Guillaume Lessard glessard at tffenterprises.com
Thu Apr 7 11:30:11 CDT 2016

A different direction would be to add a non-autoclosure variant to ?? that explicitly takes a closure.

public func ??<T>(optional: T?, defaultValue: () throws -> T) rethrows -> T {
  switch optional {
  case .Some(let wrapped): return wrapped
  case .None: return try defaultValue()

Then, the following works:

var v = Optional(7)
// v = nil
do {
  let i = try v ?? { throw NSError(domain: "", code: 0, userInfo: [:]) }
catch {

Or, even more generally, allow functions and operators that take autoclosure parameters to be used with explicit closures? I shrugged my shoulders and wrote an overload when I hit that limitation, but I wonder whether it is necessary.

Guillaume Lessard

More information about the swift-evolution mailing list