Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Platform specific code for shared watchOS/iOS classes in Swift?

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?

like image 939
BlackWolf Avatar asked Jul 22 '26 09:07

BlackWolf


1 Answers

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.

like image 143
Damiaan Dufaux Avatar answered Jul 23 '26 23:07

Damiaan Dufaux



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!