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

Adrian Zubarev adrian.zubarev at devandartist.com
Sun Feb 7 04:00:35 CST 2016


@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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160207/3a6ca71e/attachment.html>


More information about the swift-evolution mailing list