[swift-evolution] Nil-rejection operator

Haravikk swift-evolution at haravikk.me
Thu Feb 9 14:25:28 CST 2017


> On 9 Feb 2017, at 19:08, Hooman Mehr via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I think the best solution is overloading the existing ?? operator. It is very easy to do:
> 
> func ??<T,U: Error>(lhs: T?, rhs: U) throws -> T {
>     
>     if let lhs = lhs { return lhs } else { throw rhs }
> }
> 
> then you can say:
> 
> do {
>     
>     let y = try x ?? myError
>     
> } catch ...
> 
> It might even make sense to add to the standard library.

Interesting idea, but what if you actually want that error assigned to y?

I wonder if an alternative to the original proposal might be to allow throw on the right hand side? So you could do:

	let y = x ?? throw myError

That'd be a lot more explicit about what's going on than a new operator would be. It might require defining throw as being some kind of special type though that can be used to satisfy only function signatures that call for it explicitly like:

	func ??<T,U:_Throw>(lhs:T?, rhs:U) throws -> T {
		guard let lhs = lhs else { throw rhs.error }
		return lhs
	}

Same idea really, but the difference being that this wouldn't be a type that satisfies generics, but can be used for any operator that could allow a throw to occur within its operands.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170209/7f591e3c/attachment.html>


More information about the swift-evolution mailing list