[swift-evolution] [Proposal] Change guarantee for GeneratorType.next() to always return nil past end

Brent Royal-Gordon brent at architechies.com
Sat Mar 5 14:47:15 CST 2016


> Yes. My proposed .takeWhile() and .dropWhile() sequence adaptors (https://github.com/apple/swift-evolution/pull/95) would hit this case. Both of those adaptors would need to keep around extra state and in order to keep returning nil.


How much extra state? If it's merely "an extra Bool" or "wrap the inner generator in an Optional and nil it when you hit the end", it might be worth it.

(Actually, can we see the implementations you're thinking of using? Because the ones I can imagine for `dropWhile`, at least, would keep returning `nil` as long as the underlying generator did.)

> All that said, I would be strongly in favor of dropping the language about triggering a precondition failure. I'd prefer to leave it as implementation-defined behavior, which an encouragement to keep returning nil if it's easy to do so.

I think "try to return `nil` but it's okay if you can't" is the worst of all worlds from a reliability standpoint. If most, but not all, generators continue to return `nil`, then people will write code assuming that all generators continue to return `nil`.

One thing that might help is to make sure we have examples of the full range of generator behaviors—multi-pass and single-pass, nil forever and not, etc.—in the standard library and list an example of each in the SequenceType documentation along with an encouragement to test with all of them. But a lot of people will miss that.

(Another reason to lean towards always returning `nil`: it's testable. In fact, I was thinking it might be nice to have something in XCTest where you could hand it a Sequence, or perhaps a closure that creates one, and an array containing the values you expect it to have, and it would assert the basic properties we expect from a Sequence, like that the elements come out in the right order, it returns nil at the end, `underestimateCount()` is not incorrect, etc. The `nil` semantic, unlike the other possible ones, is something you could include in that test.)

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list