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.
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.
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 {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With