The language guide has revealed no trace of list comprehension. What's the neatest way of accomplishing this in Swift? I'm looking for something similar to:
evens = [ x for x in range(10) if x % 2 == 0]
The language guide has revealed no trace of list comprehension. What's the neatest way of accomplishing this in Swift? I'm looking for something similar to:
evens = [ x for x in range(10) if x % 2 == 0]
As of Swift 2.x, there are a few short equivalents to your Python-style list comprehension.
The most straightforward adaptations of Python's formula (which reads something like "apply a transform to a sequence subject to a filter") involve chaining the
map
andfilter
methods available to allSequenceType
s, and starting from aRange
:Note that a
Range
is abstract — it doesn't actually create the whole list of values you ask it for, just a construct that lazily supplies them on demand. (In this sense it's more like Python'sxrange
.) However, thefilter
call returns anArray
, so you lose the "lazy" aspect there. If you want to keep the collection lazy all the way through, just say so:Unlike the list comprehension syntax in Python (and similar constructs in some other languages), these operations in Swift follow the same syntax as other operations. That is, it's the same style of syntax to construct, filter, and operate on a range of numbers as it is to filter and operate on an array of objects — you don't have to use function/method syntax for one kind of work and list comprehension syntax for another.
And you can pass other functions in to the
filter
andmap
calls, and chain in other handy transforms likesort
andreduce
:Depending on what you're going for, though, there may be more concise ways to say what you mean. For example, if you specifically want a list of even integers, you can use
stride
:Like with ranges, this gets you a generator, so you'll want to make an
Array
from it or iterate through it to see all the values:Edit: Heavily revised for Swift 2.x. See the edit history if you want Swift 1.x.