[swift-evolution] [Pitch] Introducing the "Unwrap or Die" operator to the standard library

Brent Royal-Gordon brent at architechies.com
Fri Jun 30 15:57:35 CDT 2017


> On Jun 30, 2017, at 5:38 AM, Matthew Johnson <matthew at anandabits.com> wrote:
> 
>> 3. If we later change `throw` from being a statement to being a `Never`-returning expression, you could use `throw` on the right-hand side of `??`.
> 
> What do you have in mind here?  I don't recall any discussion of `throw` return Never.  It seems like a novel use of a bottom type that might preclude the possibility of ever having a Result type that seamlessly bridges to Swift's error handling.  


`throw` is currently a statement. Imagine, for sake of illustration, that it was instead a function. This function would take an `Error` as a parameter and throw it. It would never return normally—it would only return by throwing—so its return type would be `Never`:

	@_implicitlyTry
	func throw(_ error: Error) throws -> Never {
		try Builtin.throw(error)
		unreachable()
	}

What I'm suggesting is that `throw` should remain a keyword, but should have the semantics of this `throw(_:)` function. The parser should allow it in expression context, the `try` checker should treat it as though it was already marked `try`, and the type checker should treat it as an expression that returns `Never` but can throw.

That would then allow you to say things like:

	let lastItem = array.last ?? throw MyError.arrayEmpty

It would not have any negative effect I can think of on `Result`. In fact, trying to directly wrap a `throw SomeError.foo` statement in a `Result` would produce a `Result<Never, SomeError>`, correctly expressing the fact that the result of that particular expression can never be successful.

-- 
Brent Royal-Gordon
Architechies

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170630/c84e2c2a/attachment.html>


More information about the swift-evolution mailing list