[swift-evolution] Proposal: Python's list, generator, and dictionary comprehensions

Al Skipp al_skipp at fastmail.fm
Thu Dec 17 18:41:16 CST 2015


> On 17 Dec 2015, at 20:25, Liam Butler-Lawrence via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Comprehensions are great in Python. However, Swift can already do all of these things via for...in, map() and/or generate().

Whether Comprehensions should be introduced to the language is worth consideration (Are they vital? Probably not). But I don’t find the Swift examples using ‘for' statements particularly compelling. The ‘for’ statement needs to declare a mutable variable which is updated from within the loop. It works, but it’s not particularly elegant.

var l2: [(Int, Int)] = []
for x in 1...10 {
  for y in 1...10 where (x + y) < 8 {
    l2.append((x, y))
  }
}

It could be achieved using an expression, but it’s pretty horrible too for several reasons:

let l3 = (1...10).flatMap { x in
  (1...10).map { y in (x,y) }
}.filter { (x, y) in x + y < 8 }

(Maybe there’s a more elegant solution?)

If Swift had Comprehensions, they probably wouldn’t look exactly like the example below, but in my opinion it’s superior to the 2 code samples above.

l2 = [(x,y) for x in range(10) for y in range(10) if x + y < 8]

Al
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/08edf5e8/attachment-0001.html>


More information about the swift-evolution mailing list