objc2swift icon indicating copy to clipboard operation
objc2swift copied to clipboard

No support for #if/#else/#endif within statements

Open CodingMarkus opened this issue 9 months ago • 0 comments

E.g. the following Obj-C code is valid:

value = variable - MAX(self.otherValue,
#if DEBUG
    20
#else
    60
#endif
);

but that will produce a syntax error.

I guess the tricky part is that this construct is not valid in Swift as in Swift you need to wrap the whole expression. So you first need to turn this into

#if DEBUG
value = variable - MAX(self.otherValue, 20);
#else
value = variable - MAX(self.otherValue, 60);
#endif

Calling it a syntax error is incorrect when it is in fact valid syntax.

The trick here is to play pre-processor and once pretend DEBUG is set and once not, then you get both complete statements, which you must then again split apart as shown above.

An alternative is to not directly use conditional compilation in Swift at all but instead turn the original statement into a variable and then just make that conditional

#if DEBUG
let ValueThatDependsOnDEBUG = 20
#else
let ValueThatDependsOnDEBUG = 60  
#endif
value = variable - max(self.otherValue, ValueThatDependsOnDEBUG)

But this doesn't work if the content is more complex code, so you may just want to turn it into a code block

value = variable - max(self.otherValue, 
    {
#if DEBUG
        20 // optional `return 20` is fine, too
#else
        60
#endif   
    }()
)

Advantage of the code block is that you can have arbitrary complex statements and a code block can also capture any values from its surroundings, so you have access to all other constants/variables of the function within the code block.

CodingMarkus avatar Mar 23 '25 01:03 CodingMarkus