Swift should support comprehension expressions for Array, Dictionary, and custom containers

Originator:jlieske
Number:rdar://17246854 Date Originated:
Status:Duplicate Resolved:
Product:OS X SDK Product Version:Xcode6 beta: Version 6.0 (6A215l)
Classification:Enhancement Reproducible:Always
 
The Swift language supports many of the principles of functional programming, such as higher-order functions, immutable values, and pattern matching.  One gap in the support is generating compound data structures, including Arrays, Dictionaries, and custom containers.  Such data structures can be iterated in the “for” statement, but there is no similar convenient syntax (or documented library support) for building data structures.  It is possible to use the “map” and “filter” methods to generate Arrays from other Arrays, but other data structures are not support as either the source or destination of “map” and “filter”.

Languages like Python and Scala include convenient syntax for building data structures.  The syntax can be considered sugar for application of “map” and “filter”.  By existing as syntax, it is more likely the language can optimize the expressions (for example, calculating values inline rather than through a closure).

I propose adding syntax to Swift that allows generation of data structures through comprehension expressions.  For a strawman, the syntax would be based on Python’s comprehensions:

let evenStringArray = [x.description for x in 1...10 if x % 2 == 0]

let translationDict = [english: translate(english) for english in myEnglishArray]

let capitalizedDict = [capitalize(term): meaning for (term, meaning) in myDictionary]

let myCustomContainer = CustomContainer(x.description for x in 1...10 if x % 2 == 0)

The semantics would be based on the existing Generator protocol.  The comprehension expression returns a Generator object.  The Array, Dictionary, and custom container classes would accept Generator objects for init.

Comments

Duplicate of rdar://17194460


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!