[swift-users] Generators vs. errors

Jens Alfke jens at mooseyard.com
Tue Apr 12 13:53:07 CDT 2016

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) { … }

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.

Another possibility is to do all the failable database work up front in the `query` method that creates the Generator, but this means all the results have to be cached in memory, which isn’t scaleable. (Keep in mind I work for a database company <http://couchbase.com/> whose customers often have multi-terabyte data sets.)

I know there’s been a proposal (by Brent Royal-Gordon) to allow property accessors and subscripts to throw, which I strongly endorse, but I think we also need to allow Generators to throw. Fodder for the swift-evolution list…

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160412/8ec922ca/attachment.html>

More information about the swift-users mailing list