[swift-evolution] [Pitch] Guard/Catch

Charles Srstka cocoadev at charlessoft.com
Sun Jul 9 18:00:36 CDT 2017


> On Jul 8, 2017, at 3:08 PM, Christopher Kornher via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I am opposed to this proposal because it muddies up the language to support what is essentially an edge case. The standard way to exit a function early because an exception is thrown is to make the function itself throw, if it is part of a larger operation. The addition of a few lines of try/catch code is not a great burden and makes the termination of an an exception very clear.

Not such an edge case, if you write asynchronous code:

func doSomething(completionHandler: @escaping (Error?) -> ()) {
	guard let foo = try makeFoo() catch {
		completionHandler(error)
		return
	}

	doSomeAsyncThing(with: foo) {
		do {
			try parseTheResult($0)
			completionHandler(nil)
		} catch {
			completionHandler(error)
		}
	}
}

With the existing facilities, one must either use this rather awkward construction to make foo:

func doSomething(completionHandler: @escaping (Error?) -> ()) {
	let foo: Foo

	do {
		foo = try makeFoo()
	} catch {
		completionHandler(error)
		return
	}

	doSomeAsyncThing(with: foo) {
		do {
			try parseTheResult($0)
			completionHandler(nil)
		} catch {
			completionHandler(error)
		}
	}
}

Or, alternatively, construct a pyramid of doom:

func doSomething(completionHandler: @escaping (Error?) -> ()) {
	do {
		let foo = try makeFoo()

		doSomeAsyncThing(with: foo) {
			do {
				try parseTheResult($0)
				completionHandler(nil)
			} catch {
				completionHandler(error)
			}
		}
	} catch {
		completionHandler(error)
	}
}

Charles



More information about the swift-evolution mailing list