Would SwiftUI app code benefit from adding Python-style comprehensions to Swift?

Do you think SwiftUI app code would be more compact or readable with Python-style comprehensions?

Would SwiftUI require special support from such a feature? And if so, what might that be?

No

8 Likes

Let's compare:

numbers = [1, 2, 3, 4]
doubled_numbers = [num * 2 for num in numbers]

vs.

let numbers = [1, 2, 3, 4]
let doubled_numbers = numbers.map { $0 * 2 }

I think Swift is doing fine!

7 Likes

Not sure what do you mean by having "Python-style comprehensions" in "SwiftUI". Does python really have framework similar to SwiftUI? In addition, SwiftUI is already very compact and readable compare to many UI framework. The main improvement SwiftUI needs is more flexible customization rather than readability.

Fun fact: Chris Lattner, creator of Swift and now working on Mojo (an intended superset of Python), dislikes the Python list comprehension syntax with the post-fix conditional statements.

Timestamped, but would recommend entire interview.

2 Likes

A bit strange to bring topic of list comprehension to SwiftUI framework, as I think it should be discussed as a language topic. :thinking: If applied to SwiftUI guess it should be something like monad comprehension, like in Haskell, but it would be alien to Swift.
Also, think this could be just a syntax sugar over map (and other) functions, so maybe one could come up with macro?

I think it'd be helpful to see an example of the kind of code you'd like to use list comprehensions to write.

5 Likes

one difference between the former and the latter is the latter introduces a function scope, which means anonymous closure arguments from the outer scope no longer work, and additional try/await keywords will need to be interjected at the boundary of the map call.

i’ll also say that dictionary and set comprehensions are something from Python that i really wish Swift had, and it’s not as straightforward to translate them into Swift constructs. i usually default to writing out a reduce(into:_:) to try and imitate those.

1 Like