[swift-evolution] [Proposal]: Escaping another (unused) scope pyramide with 'guard try catch'

Thorsten Seitz tseitz42 at icloud.com
Mon Feb 8 09:56:56 CST 2016


Having foo available within the catch would be very strange as it is not yet in scope.

-Thorsten 

> Am 07.02.2016 um 11:00 schrieb Adrian Zubarev via swift-evolution <swift-evolution at swift.org>:
> 
> @Félix as far as I know you won’t be able to fall through be accident:
> 
> func throwingFuncReturns() throws -> Int? {
> 	return 42
> }
> 
> func use(foo: Int) {
> 	print(foo)
> }
> 
> func scope() {
> 	
> 	let foo: Int? // saving will work as long as the type is an optional too
> 
> 	do { foo = try throwingFuncReturns() } catch { 
> 
> 		// INITIALIZE foo OR RETURN <-- copiler will be happy
> 	}
> 	guard let unwrappedFoo = foo else { 
> 		return
> 	}
> 	use(unwrappedFoo)
> }
> 
> scope() // to be able to return
> 
> This was added in Swift 1.2 for `if else` as far as I know.
> 
> let x: SomeThing
> if condition {
> 	x = foo()
> } else {
> 	x = bar()
> }
> use(x)
> 
> So porting this behavior to a single `do try catch` will work as it did before:
> 
> func scope() {
> 	
> 	let foo: Int? // saving will work as long as the type is an optional too
> 
> 	do foo = try throwingFuncReturns() catch { 
> 		// INITIALIZE foo OR RETURN <-- copiler will be happy
> 	}
> 	guard let unwrappedFoo = foo else { 
> 		return
> 	}
> 	use(unwrappedFoo)
> }
> 
> Simplifying everything with the `guard` syntax might help us with optionals, but it automatically will close the door for `fallthrough`, because the original mechanism does not work this way. This will just confuse everyone.
> 
> It might sound absurd, but what if we remove the `do` keyword from the single `do try catch` and leave it as `try catch` with the some new behavior:
> 
> func scope() {
> 	
> 	let foo: Int? = try throwingFuncReturns() catch { 
> 		// foo IS AVAILABLE INSIDE THE CATCH BODY
> 		// INITIALIZE foo OR RETURN
> 	}
> 	guard let unwrappedFoo = foo else { 
> 		return
> 	}
> 	use(unwrappedFoo)
> }
> 
> The `do` body is needed if we want to execute more than one operation from its body, but it isn’t needed for a single `try catch` mechanism at all. So why would we want to keep the keyword here? We can omit the type from the throwing function that returns a value if no errors occurred. Plus we could apply an extra rule and assign the value from the catch body then fall through or return/break.
> 
> This also won’t have any impact on existing codebase.
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160208/06483574/attachment.html>


More information about the swift-evolution mailing list