Multi-line mathematical expressions

I took a look at Swift when it first came out, and was turned off by the inability to do multi-line mathematical expressions. With the world moving to Swift, I have started looking at Swift 5, and find it still doesn't seem to offer a solution.


In effect, instead of writing an expression like:


a = (b+(c+d)*e + f*g)


I'd prefer to do something like:


a = (b

+ (c+d)*e

+f*g)


and even better still (easy in C):


a = (b // some comment

+ (c+d)*e // some other comment

+f*g) // yet another comment


This sort of thing can be important in comprehensible scientific computation. Is there a way to do it in Swift?

Accepted Reply

Ths does not work as written (XCode 11.2 beta in playground)

     let a = (b
          + (c+d)*e
          +f*g)

Get error: Expected ',' separator (last line)


This requires a space after + on last line, and then works.

let a = (b
+ (c+d)*e
+ f*g)


Even comments are accepted. Tested the following:

let a = (b // b is 18.5
+ (c+d)*e   // c, d, e are 1.7 35.3 310.8
+ f*g)  // f, g are 1.7 18.5


Gives a: 11549.55


So, what's the problem ?

Replies

I tried out your multiline expression in an Xcode playground (Swift 5.1.2). You separate at addition (probably also subtraction), but not at multiplication (probably also for division). Didn't try the comments, but, like C/C++, inline comments should be treated like whitespace during the lexical analysis, so, it should work.

Has to do with the associativity attributes of the operators.

Ths does not work as written (XCode 11.2 beta in playground)

     let a = (b
          + (c+d)*e
          +f*g)

Get error: Expected ',' separator (last line)


This requires a space after + on last line, and then works.

let a = (b
+ (c+d)*e
+ f*g)


Even comments are accepted. Tested the following:

let a = (b // b is 18.5
+ (c+d)*e   // c, d, e are 1.7 35.3 310.8
+ f*g)  // f, g are 1.7 18.5


Gives a: 11549.55


So, what's the problem ?

Thank you.