Support for more operators in #if swift build configuration option

Hi!

I've recently read a conversation on Twitter around why this piece of code does not compile:

#if swift(<4.2)
...
#endif

Right now, the way to express this is by using ">=" and negating:

#if !swift(>=4.2)
...
#endif

I think the first syntax reads more natural than the second, and the "!" is easy to miss in a code review, for example.

Is there interest in supporting a more flexible syntax for #if swift() with more operators, like "<"? The original proposal actually left this point open to extension: https://github.com/apple/swift-evolution/blob/master/proposals/0020-if-swift-version.md

The argument to the configuration function is a unary prefix expression, with one expected operator, >=, for simplicity. If the need arises, this can be expanded to include other comparison operators.

What do you think? Do you think adding support for "<" is a good idea? Some other operators?

I've already implemented the required changes in the parser in local, but I wanted to ask the community so that this is useful to as many people as possible.

Thank you very much,
Daniel

3 Likes

It's come up before! There's even an implementation in SR-6852, although it looks like it's bitrotted a bit. The decision back then was that the Core Team needed to get the chance to discuss it and decide whether it needed a formal review, but I can't really think of a reason not to allow it. (I'm pretty sure there have been previous threads on this too, but I can't find them at the moment. "if swift" turns out to be a common search term.)

Aside: The term to use to is "compilation condition", since "build configuration" already means something else in Xcode.

2 Likes

+1, I don't see any reason to forbid <.

2 Likes

Thanks for the feedback! I didn't know this came up before. My current implementation (https://github.com/danielmartin/swift/commit/883b61a24f21ec0f6f2a54c8beee08bdec7099e2) is similar to the existing one. I'd also like to improve the diagnostic messages a little bit: Saying "expected a unary comparison, such as..." to me means that there are other unary comparison operators that are supported, and ">=" is just an example, which is not true. I may be wrong because I'm not a native English speaker.

What are the next steps for this? Should I write a formal proposal for review, a PR...? If this feature landed, I plan to also write a Swift refactoring action for Xcode that can convert between the two. I think that would help with the discoverability of this new language feature.

Thank you very much,
Daniel