[swift-users] Generators vs. errors

Brent Royal-Gordon brent at architechies.com
Wed Apr 13 01:15:32 CDT 2016

> On Apr 12, 2016, at 11:53 AM, Jens Alfke via swift-users <swift-users at swift.org> wrote:
> What should one do, when implementing a Generator, if the underlying data source can experience errors? Generator.next isn’t allowed to throw, only to return nil at the end of the sequence.
> The only idea I can think of is to add an `error` property to my Generator implementation, and request that the caller check it after the iteration ends, and/or a `checkForError()` method that can throw an error if there is one:
> 	var q: Query = db.query(…)
> 	for (row in q) { … }
> 	q.checkForError()
> As the example implies, this problem comes up when creating Swift bindings for database iterators/cursors. Generator is the obvious protocol to implement, especially since without it you don’t get the idiomatic for/in loop, but the `next` method does have to hit the database, so it has the possibility of I/O errors.

What I might do is use a block to make sure you can't forget the `checkForError()` method:

	let query = db.query(…)
	try query.withResults { results in
		// `results` is a SequenceType you can iterate over.
		// You can only get at it by calling `withResults` on a Query, and it becomes invalid once 
		// `withResults` returns.
		// If `results` encounters an error, it terminates early.
		for row in results {
			// Use your row

Brent Royal-Gordon

More information about the swift-users mailing list