skaak
skaak

Reputation: 3018

Swift if directive quirk

Suppose I have a complex chain of ifs. Now I want to be sure that one of the conditions are triggered, so I add the final line to notify me when nothing was triggered.

if condition1 ...
else if condition2 ... 
else if condition3 ...
else print( "Ooops nothing triggered" )

Since I only want to print this in DEBUG mode, I wrap the final line

#if DEBUG
else print( "Ooops nothing triggered" )
#endif

and I get the strangest errors. "Closure expression is unused" and "Expected expression".

Here is some simple working code to illustrate with.

        let x = Int ( arc4random_uniform ( 100 ) ) - 50

        // This works
        if x > 0      { print ( "Positive" ) }
        else if x < 0 { print ( "Negative" ) }
        else          { print ( "Oops - neither" ) }

        // After adding the #if this does not compile
        if x > 0      { print ( "Positive" ) }
        else if x < 0 { print ( "Negative" ) }
        #if DEBUG
        else          { print ( "Oops - neither" ) }
        #endif

Obviously Swift's conditional compilation here fails. I wonder why and ask how to to do this so that the test is only applied in DEBUG mode?

FWIW I am not interested in e.g. using switch - the actual logic is complex. How to do this with ifs and else ifs if possible please?

Upvotes: 0

Views: 63

Answers (1)

Sweeper
Sweeper

Reputation: 274423

These #ifs don't really work like those preprocessor directives in C. They

According to the grammar, the syntax of these directives are the following:

if-directive-clause → if-directive compilation-condition statements(opt)
elseif-directive-clauses → elseif-directive-clause elseif-directive-clauses(opt)
elseif-directive-clause → elseif-directive compilation-condition statements(opt)
else-directive-clause → else-directive statements(opt)
if-directive → #if
elseif-directive → #elseif
else-directive → #else
endif-directive → #endif

Note that an if-directive-clause consists of #if, then a compilation-condition, then some statements. Not just anything, but statements.

else { print ( "Oops - neither" ) }

is not a statement (or a list of statements).


How about putting the #if inside the else block? That is guaranteed to be a statements:

if x > 0      { print ( "Positive" ) }
else if x < 0 { print ( "Negative" ) }
else          { 
#if DEBUG 
    print ( "Oops - neither" ) 
#endif 
}

Upvotes: 2

Related Questions