[swift-evolution] [Pitch] Change location of 'try' for infix operators

Ben Rimmington me at benrimmington.com
Tue Oct 11 01:47:56 CDT 2016


> On 11 Oct 2016, at 07:16, Karl wrote:
> 
> You might expect this code to work:
> 
> func aFunction() -> Int?       { return 5 }
> func bFunction() throws -> Int { return 4 }
> 
> let value = aFunction() ?? try bFunction() // ERROR: Operator can throw but expression is not marked with a ‘try'
> print(value)
> 
> Instead, you must put the ‘try’ before the entire expression:
> 
> let value = try aFunction() ?? bFunction()
> 
> This is awkward, since aFunction() doesn’t throw.
> I propose we change the grammar to allow the first example and disallow the second, consistent with the idea that throwing calls are ‘marked’ by using the try keyword.

The `??` function rethrows an error from its rhs operand.

	@_transparent
	public func ?? <T>(optional: T?, defaultValue: @autoclosure () throws -> T)
	    rethrows -> T {
	  switch optional {
	  case .some(let value):
	    return value
	  case .none:
	    return try defaultValue()
	  }
	}

<https://github.com/apple/swift/blob/5d3a7f7c230ae238c848a06f58b58c7e68fb5ed0/stdlib/public/core/Optional.swift#L415-L424>

-- Ben

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


More information about the swift-evolution mailing list