Swift strategies for "#if os(tvOS)" needing syntactically complete code blocks

I found the Objective-C and Swift conditional switches for detecting Apple TV (good docs, Apple).


However, I noticed this comment in the docs:

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.


I've already found a situation where this seems to be messy. Since tvOS doesn't include WebKit, I have a class declared as such in Objective-C:


#ifdef TARGET_OS_TV
     @interface MyTableViewController : UITableViewController
      {

#elif TARGET_OS_IOS
     @interface MyTableViewController : UITableViewController
      <UIWebViewDelegate> {
#endif

...
}


But how would you do that in Swift? I'm guessing this is not syntactically complete code:

#if os(tvOS)
     public class MyTableViewController: UITableViewController {

#elseif os(iOS)
     public class MyTableViewController: UITableViewController, UIWebViewDelegate {
#endif


Would you have to declare the whole class separately? Any other strategies?

Accepted Reply

You need to write something like this:

public class MyTableViewController: UITableViewController {
    //...
}
#if os(iOS)
    extension MyViewController: UIWebViewDelegate {}
#endif

Replies

You need to write something like this:

public class MyTableViewController: UITableViewController {
    //...
}
#if os(iOS)
    extension MyViewController: UIWebViewDelegate {}
#endif

Correction for Objective-C, so I don't ***** anyone up:

#ifdef TARGET_OS_TV


should be

#if TARGET_OS_TV

Excellent, thank you. Never thought of using extensions that way.