[swift-evolution] Removing enumerated?

Jonathan Hull jhull at gbis.com
Tue Jan 31 17:56:56 CST 2017


> On Jan 31, 2017, at 12:46 PM, Ben Cohen via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> // apply alternating view background colors
>> for (i, view) in views.enumerated() {
>>     view.backgroundColor = i % 2 ? bgColor1 : bgColor2
>> }
>> 
> 
> This is an interesting one because it highlights something else I think is missing from the std lib: Sequence.cycle, which would make an infinite sequence by repeating a sequence, enabling what I think is probably a readability win in some cases:
> 
> let colors = [bgColor1, bgColor2].cycle
> for (color, view) in zip(colors, views) {
> 	view.backgroundColor = color
> }

This is a common enough need for me that I have built a special class for it.  Here is the code in case it is useful to others trying to do the same thing:
https://gist.github.com/jonhull/b9cd8a50abca16ea49eade2c91edf8a2

At it’s heart, it takes an array (or a single value) and turns it into an endless repeating collection.  It also has facilities for random output, and to compose with other sources, allowing complex repeating patterns from simple sources.  I originally made it for creating fill patterns in a drawing framework (e.g. stripes like your example above), but I have found it generally useful over time.

Thanks,
Jon
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170131/b79c5f9f/attachment.html>


More information about the swift-evolution mailing list