3

I am currently building an iOS app with a watchOS app extension. I have certain classes that are shared between both apps, and they are largely identical on both platforms, but with certain variations. I am wondering how this is best implemented. Right now I use the following:

#if os(watchOS)
private var watchOSOnlyProperty: Any?
#endif

or

#if os(iOS)
func iOSOnlyMethod() {
    ...
}
#endif

While this works, it gives several problems since XCode seems to be pretty confused about this. Indentation, autocompletion and the list of methods are all a bit off when using this syntax.

What is the proper way to do this? How can you add iOS/watchOS-specific properties & methods to shared classes in Swift?

BlackWolf
  • 5,239
  • 5
  • 33
  • 60
  • 1
    That is the proper way – Paulw11 Aug 06 '17 at 08:14
  • Hm... this produces so many problems for me in XCode that I would consider it not really viable, though. For example, autocompletion has pretty much stopped working completely for me for classes that use this. Any alternatives? – BlackWolf Aug 06 '17 at 08:15
  • Create different source files for the different targets. This should work though. Try deleting your derived data – Paulw11 Aug 06 '17 at 08:21
  • didn't help unfortunately :/ neither in XCode 8 nor XCode 9 beta 4. I did notice the problem only occurs inside `#if os(watchOS)` blocks, `#if os(iOS)` seems unaffected. – BlackWolf Aug 06 '17 at 09:37

2 Answers2

2

Code separation

There are two ways to separate code

  • Use #if os(...) like you suggested.
  • Use separate files for the different targets.

Auto completion

Xcode will only autocomplete code for your current selected target. Xcode target selector

If you want autocompletion for code inside #if os(watchOS) blocks then you need to change your current target (via the toolbar) to the wathOS target.

Damiaan Dufaux
  • 4,427
  • 1
  • 22
  • 33
0

You can add a C preprocessor flag in the Build Settings for the Watch app target.

-DWATCHOS

Then

#ifdef WATCHOS
// watchOS code here
#else
// iOS code here
#endif

will work.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153