Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conform to protocol on DEBUG configuration only

I'm trying to enable class protocol when DEBUG flag is set:

#if DEBUG
 class LoginViewController: UIViewController, UITextFieldDelegate {
#else
 class LoginViewController: UIViewController {
#endif
     //...
 }

It does not compile though, "Expected declaration" on #else line.

like image 247
Cfr Avatar asked Apr 30 '26 11:04

Cfr


2 Answers

Preprocessor directives in swift are not the same as you might be used to using.

The Apple documentation on the subject notes that anything contained between #if/#else/#endif statements must be valid swift statements on their own.

In contrast with condition compilation statements in the C preprocessor, conditional compilation statements in Swift must completely surround blocks of code that are self-contained and syntactically valid. This is because all Swift code is syntax checked, even when it is not compiled.

Because your statements are fragments (ending in an open brace), they do not compile.

You may have to do something like the following to accomplish what you want:

class LoginViewController: UIViewController {
  ...
}

#if DEBUG
class DebugLoginViewController: LoginViewController, UITextFieldDelegate {
  (just add the UITextFieldDelegate code here
   let LoginViewController handle the rest)
}
#endif

Then you'll use a #if DEBUG/#else/#endif where you're instantiating your view controller to choose the DebugLoginViewController or not.

like image 138
Ian MacDonald Avatar answered May 02 '26 00:05

Ian MacDonald


Ian MacDonald has already explained the reason for the compiler error perfectly, and proposed a good solution.

Just for the sake of completeness, here are two more possible solutions:

  • Declare the text field delegate methods in an extension which is only defined in the DEBUG case:

    #if DEBUG
    extension LoginViewController : UITextFieldDelegate {
        // ...
    }
    #endif
    
  • Define a custom protocol which is either aliased to UITextFieldDelegate or defined as an empty protocol:

    #if DEBUG
    typealias MyTextFieldDelegate = UITextFieldDelegate
    #else
    protocol MyTextFieldDelegate { }
    #endif
    
    class LoginViewController: UIViewController, MyTextFieldDelegate {
        // ...
    }
    
like image 26
Martin R Avatar answered May 02 '26 01:05

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!