[duplicate] @autoclosure for nil coalescing operator

Currently, the shortest syntax to throw an error on unsuccesful Optional unwrap is try someOptional ?? { throw SomeError() }().

While the closure wrapping isnt too bad, this feels like the perfect match for the use of @autoclosure. Nil-coalescing is already lazy, but making the rhs @autoclosure allows us to strip the ugly {...}() syntax. Afterall, if we were to do this with a custom operator, like objc.io do here https://twitter.com/objcio/status/1100437285684822017?s=21 , we would likely make rhs @autoclosure as well.

What do you guys think? To me it feels like a natural use for Swift’s existing @autoclosure feature, and a purely additive change that doesnt really break any reasonable code. I havent researched the current implementation of ?? in detail, but will do if these forums think its something worth pursuing.

There was a recent discussion on this: Combining ? with throwing when there's no reasonable default

thanks, to be fair I did give it like 2 google attempts but couldnt find that thread. Closing this and moving over

I would have hoped I can mark this thread resolved or something (cant find that option, at least on mobile).

I will let it sit here but anyone with the power feel free to get rid of it.

BTW you can write a custom function that traps and call it on the RHS.

For example:

func unreachable<T>() -> T {
  return fatalError("unreachable") as! T
}

let value: Int? = 1
let unwrapped = value ?? unreachable()
1 Like

I'll close it.

1 Like